Multithreading: APM and the continuation passing style

In this post, we’ll take a look at the last option we can use for the rendezvous phase of the APM pattern. This last option is based on the continuation passing style principle. In practice, this means that we need to wrap up the work that should be performed after the async task ends in a closure and pass it to the BeginXXX method.

There are some cases where this might not be a viable option. After all, having to pack everything that is needed into a closure so that it can be executed on the completion of the async task might not be so easy as it might appear at first sight (keep in mind that the thread pool should be used for “small” tasks only!). Before going on, lets see the code that uses this approach:

var request = WebRequest.Create("",,);
var evt = new ManualResetEvent(false);
var result = request.BeginGetResponse( asyncResult => {
        WebResponse response = null;
        try {
            response = request.EndGetResponse(asyncResult);                       
        } catch (WebException ex) {
            //log error…                       
        //rest of work needs to go here                   
    , null);

As you can see (and since I was using a console app), I had to use an event to stop the program from ending before I received the results (don’t forget that  threads from the pool are background threads). As you can see, the comment “rest of work” represents the place where you should put the rest of the things that need to be done.

And that’s it. Now that we’ve explored the four waiting available options, it’s time to explore how we’d implement the Begin/End methods and talk about the details that go in an IAsyncResult implementation. Keep tuned for more on multithreading.


~ by Luis Abreu on June 10, 2009.

Leave a Reply

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

You are commenting using your 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: