Plan for Long-running processes by using Asynchronous Pages

There may be several situations when your web pages need to handle long-running processes, for example, query information from a slow database, work with the file system, etc. In this case, you’d need to use asynchronous pages.

First you need to understand that asynchronous pages aren’t actually faster, than their synchronous counterparts. Using them won’t affect the speed of your site, just the scalability of it. The second thing to know is that you shouldn’t use the traditional multithreading ways when you are working with ASP.NET. ASP.NET serves incoming requests from its on thread pool; one thread is responsible for the whole lifetime of the request. When you use the Threading namespace, you are getting a thread from the very same thread pool ASP.NET itself uses. So you shouldn’t do it. Instead you should use asynchronous pages, which in fact gets their working threads from another thread pool, thus freeing up the ones in ASP.NET’s, which it can use to serve more requests.

The way to implement this behavior is to use asynchronous pages. To mark a page as asynchronous, you’d simply need to add the Async property to the page directive, and set it to true:

<% @Page Async=”true” … %>

Second thing to do is to add the AddOnPreRenderCompleteAsync method to your page, in the Page_Load event, for example. In this method, you need to define two event handlers, a BeginEventHandler, and an EndEventHandler. By doing so, you modify the running of the page life-cycle. After the PreRender event, the page will call the method specified in the BeginTask event handler, processes the asynchronous task, and then calls the EndTask method, just before moving forward to PreRenderComplete.

When you plan to implement more asynchronous operations in a single page, you should use the Page object’s RegisterAsyncTask method. You can pass an instance of PageAsyncTask object, that encapsulates all request details. The signature of a PageAsyncTask looks like this:

PageAsyncTask(delegate begin, delegate end, delegate timeout, object state)

You can set the timeout duration in the Page directive, by setting the AsyncTimeout property. The default value is 45 seconds. Note that you cannot set different timeouts for your asynchronous operations, only one for all.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s