Async in asp.net 2.0- don’t forget that iAsyncResult!

One of the points of confusion I’ve seen wrt these new asp.net features is people trying to use them (and getting no farther than head banging) with random functions.

.NET 2.0 makes a lot of asynchronous stuff much easier with the Event Driven Asynchronous Pattern.

The BackgroundWorker sets up the entire package for  you and is a great solution for Windows Forms.

But with the ASP.NET 2.0 methods, you must call out to methods that already have BeginInvoke/EndInvoke and that return IAsyncResult. It’s easy to do with classes that already do this – like the new SQLCommand Async functions (eg. BeginExecuteReader/EndExecuteReader) or calls using HTTPRequest to pull down data from another website (eg an RSS Feed). But what about doing long running processes that don’t have .NET (or 3rd party) calls that implement the async pattern? What if you have a website that does the ever popular Fibonacci calculation? (Not really “ever-popular”, though it is the common example of long running method used in MSDN docs ;-)).

The grown-up way is to create a delegate for your synchronous method and then call BeginInvoke and EndInvoke. Here’s some help with that.

An easy way that doesn’t require mucking with delegates is to stuff the function into a web service then use the web services async functionality (which come for free when you build a web service proxy through Visual Studio). Prior to VS2005, we had only the Begin/End methods availalbe. VS2005 has those plus a new pair that ift into the Event Driven Async Pattern: myMethodAsync & myMethodCompleted. You can see both of these in the above link.

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.