LA.NET [EN]

Jun 10

Multithreading: the APM pattern and polling for completion

Posted in C# Multithreading      Comments Off on Multithreading: the APM pattern and polling for completion

In this post we’re going to take a look at how we can use polling to see if an asynchronous task has completed. As we’ve seen, the IAsyncResult instance returned from the BeginXXX method (that started an asynchronous task) has an IsCompleted property that returns true when the task is completed.

In practice, this means that you can use this property for polling the status of the task. For instance, here’s some  based on the previous example that relies on this property:

var request = WebRequest.Create("http://msmvps.com/blogs/luisabreu",,);
var result = request.BeginGetResponse(null, null);
Console.WriteLine("async request fired at {0}", DateTime.Now);
while (!result.IsCompleted) {
   //do something "inexpensive"
}
WebResponse response = null;
try {
    response = request.EndGetResponse(result);
}
catch (WebException ex) {
    //log error…
}

As you can see, it’s similar to the previous example. The main difference between IsCompleted and waiting on the AsyncWaitHandle property is that the IsCompleted property won’t block the thread. However, you should be careful with the instructions you put inside the while cycle:  don’t build a manual spin that does nothing (that is really inefficient!) and that ends up consuming precious CPU resources, ok?

And that’s it. On the next post we’ll talk about the last option (which is the one I use more often) for handling the completion of an async task started through the APM pattern.