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.

Advertisements

~ by Luis Abreu on June 10, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: