Skip Navigation LinksHome > Categories > Code from a Category

Making an asynchronous call in ASP.NET on synchronous pages

User Name: codelecturer
Name: Mike Chauhan
Contact Me:
Home Page:
6 years of total IT experience including programming, application development, System Maintenance . 3 years of Experienced and expertise in .Net Framework VB, Visual Basic.Net, ASP.Net 2.0, 3.5 and AD... [More]
Viewed Times: 1660
Add Date: 01/08/2012
If you need to make an asynchronous method call from an ASP.NET page the usual technique is to use asynchronous pages to allow lengthy operations to execute without holding up the currently executing thread.

However, there are scenarios where it will not be possible to implement an asynchronous page. This affected me most recently when I had a large data store sitting in the ASP.NET cache that was being refreshed from an incredibly slow web service call. If the data drops out of the cache then it needs to be refreshed, yet this could happen on any page in the application. Added to this was the fact that this was a CMS integration project where I did not have control over any of the pages in the administration interface for the CMS.

So, asynchronous pages were out. One strategy is, of course, to change the way you store and refresh the data store in the cache through a local caching mechanism of last resort. However, it would be preferable to find a way of sending off an asynchronous refresh request if at all possible.

The code below shows how it’s done. The helper class below implements a "fire and forget" asynchronous call by taking a thread from the thread pool and firing it at a delegate.

To implement the class, declare a delegate for the method that you want to call asynchronously and use the helper class to fire off a thread on it. The code sample below shows how this can be done on an ASP.NET page. The method MyMethod is called on a new thread while the page continues to execute and returns a response to the browser.

Care should be taken here because the new thread will not have any awareness of the orginal request context. If you want it to be able to access the context (and therefore the cache) then you will need to pass a reference to the context in with your delegate, as shown below.

Post a Comment

Name: (Optional)
Email: (Optional, you can get an email if somebody replys your comments)*
Email me if somebody respons my comment below:
Enter Text
as Below:
(case insensitive, if hard to read, click the "get a new one" button)
* Your email address will not be shared with any third parties for any reason.
** Maximum 1000 charactors.