Multithreading: APM and the continuation passing style

Published Wed, Jun 10 2009 13:35

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("http://msmvps.com/blogs/luisabreu");
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                   
        evt.Set();
    }
    , null);
evt.WaitOne();

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.

Filed under: ,

Comments

# 9eFish said on Wednesday, June 10, 2009 9:43 PM

9efish.感谢你的文章 - Trackback from 9eFish

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above:  

Search

This Blog

Tags

Community

Archives

Syndication

Email Notifications

News




  • View Luis Abreu's profile on LinkedIn


    Follow me at Twitter

    My books

    Silverlight 4.0: Curso Completo

    ASP.NET 4.0: Curso Completo

    Portuguese LINQ book cover

    Portuguese ASP.NET 3.5 book cover

    Portuguese ASP.NET AJAX book cover

    Portuguese ASP.NET AJAX book cover