Asynchronous Calls in asp.net2.0
.Net Framework 2.0 makes life so easy with asynchronous calls from pages. I remember in asp.net1.x we had to do so much to achieve the same behaviour, but we are lucky that in asp.net2.0 its very easy.
Again there are more than one ways to implement asynchronous calls in asp.net2.0 and you may be asking which pattern to use.
The first way is to use the AddOnPreRenderCompleteAsync
AddOnPreRenderCompleteAsync (
new BeginEventHandler(BeginAsyncMethod),
new EndEventHandler (EndAsyncMethod)
);The second way is to use the PageAsyncTask and RegisterAsyncTask
PageAsyncTask task = new PageAsyncTask(
new BeginEventHandler(BeginAsyncMethod),
new EndEventHandler(EndAsyncMethod),
new EndEventHandler(TimeoutAsyncMethod), null
);
RegisterAsyncTask(task);
The second way is preferrably better as it has the following advantages over the first way.
- RegisterAsyncTask also take an additional parameter for timeout.
- More than one RegisterAsyncTask can be called in one Request.
- The fourth parameter of RegisterAsyncTask can take state of the Begin Method.
- To the End the Timeout Method RegisterAsynTask gives you handy objects (ie HttpContext.Current, impersonation and culture).
Remember to put Async="true" attribute in the @ Page directive for any of the preferred methods mentioned above.
Also for Webservices we can use this following pattern:
theproxy.MyMethodCompleted += new MyMethodCompletedEventHandler (OnMyMethodCompleted);
theproxy.MyMethodAsync (...);
...
void OnMyMethodCompleted (Object source, MyMethodCompletedEventArgs e)
{
// This is called when MyMethod completes
}For any long running tasks always try to use AsyncMethods as it never ties up threads from the thread pool.
In msdn you will find this great article in this topic: Asynchronous Pages in asp.net 2.0.