Search code examples
c#c#-4.0asynchronouscallbackmanualresetevent

Console app exits before callback is executed


I have a console app that executes a class method (in a different project). This method performs a POST to a webservice asynchronously (this is a lengthy operations of 3 minutes) and has a callback that returns the number of records affected by the POST. In the meantime the program continues doing other things that takes less than 3 minutes and the program exits before the callback returns.

In the past I have used a ManualResetEvent as depicted below to prevent completion but in this case my method is in a different class library that I would like to keep as clean as possible.


static ManualResetEvent resetEvent = new ManualResetEvent(false)

static void Main()
{
     CallAsyncMethod();
     // Do other things...
     resetEvent.WaitOne(); // Blocks until "set"
}

void AsyncMethodCallback()
{
     // Do processing on completion...
     resetEvent.Set(); // Allow the program to exit
}

I would appreciate any help in coming up with a clean pattern to accomplish this without polluting the called class with execution flags.


Solution

  • If you can (in particular, if you're using .NET 4), make your CallAsyncMethod return a Task or Task<T>. Then you can easily attach a continuation, wait for it to complete etc. If the only purpose of the callback is to get the number of records, returning a Task<int> would be ideal. You can use TaskCompletionSource<TResult> so populate the result really easily within the async method, so you don't need the callback at all within your main class, which would have a main method something like:

    static void Main()
    {
         Task<int> asyncTask = CallAsyncMethod();
         // Do other things...
         int count = asyncTask.Result;
         // Do anything you need with the count
    }
    

    The new async features in C# 5 are designed to work well with Task<T>, so you'll be all ready to embrace the new version when it arrives.