Asynchronous Programming with ASP.NET

Brij
Posted by in ASP.NET category on for Intermediate level | Points: 250 | Views : 18675 red flag
Rating: 5 out of 5  
 3 vote(s)

This article discusses one of most unused but very useful feature of ASP.NET that is Asynchronous programming


 Download source code for Asynchronous Programming with ASP.NET

Introduction:

Have you ever tried using Async pages in asp.net? 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.



Fig: How Asynchronous page works

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, it implements IAsyncHTTPHadler. Lets have a comparative look on Synchronous vs Asynchronous page processing.


 
Fig: Synchronous vs Asynchronous page processing
 

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

    	<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Async.aspx.cs"
        Inherits="Async" Async="true" %>
    

- 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)
    {
        //Write you code here
    }
    
And your EndTask method would be like
    private void EndTask(IAsyncResult ar)
    {
         //Write you code here
    }
    

- 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)
    {
        Page.AddOnPreRenderCompleteAsync(BeginTask, EndTask);
    }
    

- 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()
    {
      //Write you disposal code here
    }
    
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.

Conclusion:

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 share your feedback that will be very helpful in my upcoming writings.
Page copy protected against web site content infringement by Copyscape

About the Author

Brij
Full Name: Brij Mishra
Member Level: Starter
Member Status: Member,Microsoft_MVP
Member Since: 4/9/2010 1:43:09 PM
Country: India
Cheers, Brij Microsoft MVP - ASP.NET/IIS http://brijbhushan.net
http://brijbhushan.net
Brij is a Microsoft MVP in ASP.NET/IIS. He is a very passionate dotnet programmer.He is fond learning latest microsoft technologies and love to share the knowledge to others. Visit his blog: http://brijbhushan.net Follow him on Twitter: @brij_bhushan

Login to vote for this post.

Comments or Responses

Posted by: Chvrsri on: 6/20/2011 | Points: 25
Hi Brij,

Very neatly explained !!! Nice article 5 from me !!!
Posted by: Akiii on: 6/20/2011 | Points: 25
Good Topic selection......
Keep posting....

Thanks and Regards
Akiii
Posted by: Brij on: 6/22/2011 | Points: 25
Thanks to all!!

-Brij
Posted by: Tiger8891 on: 6/23/2011 | Points: 25
Very Nice Article...
Posted by: Susanthampy on: 6/24/2011 | Points: 25
Good........!
Posted by: Vivekr on: 2/22/2013 | Points: 25
Hello Brij....

Can you please do me a favour...... i have three thread process running in my website....... i want to bind data to the gridview when the thread completes one by one..... pleas help me........

Login to post response

Comment using Facebook(Author doesn't get notification)