One can use Asynchronous methods in ASP.NET when we expect long running I/O, database queries or Web Service/WCF tasks to release the .NET CLR thread for reuse by other ASP.NET requests from the thread pool. Allows your app to scale well and ensures that some users performing long running tasks do not hold up other users.
So using either the AddOnPreRenderCompleteAsync or the RegisterAsyncTask methods, one can start coding async tasks. The former has some drawbacks, like multiple calls on it are executed only sequentially..call it the "Async synchronous" method :-) while RegisterAsyncTask can work multiple threads in parallel and maintain/flow the HttpContext as well. Using the former as an example, say in the Page_Load event
if (!IsPostBack) { AddOnPreRenderCompleteAsync( new BeginEventHandler(BeginAsyncProcessing), new EndEventHandler(EndAsyncProcessing) );
}
Next you can define your event handler with the following signature for the event handler delegate. For eg,
{ IAsyncResult BeginAsyncProcessing(object sender, EventArgs e, AsyncCallback cb, object state)
// TODO: Perform async operation and return IAsyncResult
}
You need to pass in an AsyncCallback object, and the method returns the result in an IAsyncResult object. Similary for the asynchronous end event handler below.
{ void EndAsyncProcessing(IAsyncResult ar)
//TODO: Get results of asynch operation
}
I shall be following up this post with how to do the asynchronous processing another way using the generic ASHX HTTP handler.