ASP.NET: Asynchronous Programming

Click here to download the sample code


Have you ever tried using Async pages in Did you ever explore it in
respect of ASP.NET?

If No. This is the article for you. In this, I will be discussing, what is Async
programming? what are the benefits? Async in respect of ASP.NET and its uses
and lots more.

Async programming:

In a literal meaning, Asynchronous operation means that a process operates independently of other processes. If there are multiple operations, All that can be handled different processes/thread without waiting to complete the other ones. So here in coming sections, we will be discussing, how Asynchronous programming comes into the picture in ASP.NET.

Async Programming in ASP.NET:

Normally the kind of websites that we make are not scalable enough that could have been. These websites are very limited and confined. ASP.NET provides us a way to develop our websites more scalable.

Now lets discuss Async programming in respect of ASP.NET. We need to understand how ASP.NET processes the request. When ASP.NET receives a request from a Client, a thread is assigned to request from Thread pool that takes care all the request processing for the request. In normal cases, the thread is kept engaged till the request completes like this
instantiates the page, runs the event handling code and returns the rendered HTML. If this request
requires some long running process or wait for some I/O process then it takes. In the mean time if another request comes, the other free thread is assigned to the request. But thread pool has a limited number of threads and if requests continues pouring when all the thread were exhasted.ASP.NET is forced to deny further requests and User will start getting Server Unavailable errors. Which you seriously does not want. Let’s have a pictorial view.

Asynchronous page flow

So in this article I am going to discuss, one of the most unused features of ASP.NET but that will be really helpful for developing highly scalable and available applications.

Details of Async Programming in ASP.NET:

As we already discussed the need and benefits of Async programming in ASP.NET. Lets discuss how ASP.NET leverages Async programming. There is a series of steps/method gets executed ASP.NET loads a page or post back occurs. Every ASP.NET process goes through HTTP pipeline and the finally served by an Handler. A normal handler implements IHTTPHandler. Even if have ever implemented the Handler you must be knowing it. But in case of Async pages a normal HTTPHandler cannot serve the purpose. ASP.NET provides another type of Handler that serves it, that implements IAsyncHTTPHadler. Lets have comparative look on Synchronous and Asynchronous page processing.

Page Life cycle events flow: Synchronous vs Asynchronous

An example of Asynchrounous programming:

So now lets see a example: How to implement Asunchrponous page with ASP.NET.

I have created a sample page and would be showing step by step.

- Create a page and set Async=”true” at page directive of aspx page as

    	&lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="Async.aspx.cs"<br />        Inherits="Async" Async="true" %&gt;

- Now at code behind, we need to two methods say BeginTask and EndTask. BeginTask takes some parameters and returns IAsuncresult ad start the task that takes long. and EndTask will be called when the task gets completed and is
handled by another thread. The BeginTask woul be like

    private IAsyncResult BeginTask(object sender, EventArgs e, AsyncCallback cb, object state)<br />    {<br />        //Write you code here<br />    }

And your EndTask method would be like

    private void EndTask(IAsyncResult ar)<br />    {<br />         //Write you code here<br />    }

- We also need to tell the Page these BeginTask and EndTask methods. So that it will be called appropriately. It will done on Page_Load as

    protected void Page_Load(object sender, EventArgs e)<br />    {<br />        Page.AddOnPreRenderCompleteAsync(BeginTask, EndTask);<br />    }

- You need to write your code at Page_PreRenderComplete

- We have to override dispose method, that should dispose any connection that we open.

     public override void Dispose()<br />    {<br />      //Write you disposal code here<br />    }

I have attached one sample code for example in attachment. That gets the data from database and bind it to the GridView.Assume that data is very large and your database is at some remote machine then it may take long to load.So in that senario, it will be very helpful. You can change the connection string and query to run the sample.

When to use Async pages:

We have discussed a lot about Async pages. But is it advisable to use this in every application. Absolutely not.Because to change the thread between the operation, requires context switching, saving temporary data and lots more. This is itself not very simple operation. So one need to intelligently select this option.

Actually when we have pages that involves some Non ASP.NET thread like getting result from some Web services, printing several pages, reading a file from remote places. These type of Applications are the best candidates of Async programming. Because say, If you have a page that requires to access a file from remote location. So while accessing the file system from the remote location, the ASP.NET thread gives the control to another thread for accessing the file. And ASP.NET thread does not do anything till it receives the result from continuation thread. And if it takes long your ASP.NET site provide less throughput. So for better throughput, you can engage the thread to serve another request.


Asynchrounos programming in ASP.NET , one of most unused programming in ASP.NET. But this technology can be very useful in several scenarios as we discussed above.

Please provide your valuable feedback, it will help me a lot in my upcoming writings.

About these ads

2 thoughts on “ASP.NET: Asynchronous Programming

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