Jun 10

Multithreading: APM and the continuation passing style

Posted in C# Multithreading      Comments Off on 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.