Writing Asynchronous Web Pages with ASP.NET- Part 1

Asynchronous programming is not new but recently getting precedence over synchronous model. As user experience is now our top priority, we provide our considerable amount of effort to provide user a seamless experience. Asynchrony is one way to achieve it. I am going to write a series of posts on this topic.

Normally in our day to day programming,  web pages that we write, executes synchronously. But having lot of data on a single page mar the performance of web page. Even sometimes, we have lot sections in our page that can be loaded independently and parallely. Keeping it in mind, Microsoft introduces new way of writing asynchronous programming (Task based asynchronous pattern) with .NET 4.0 and further simplified it using async and await keyword in .NET 4.5. Currently, There are three pattern are available for writing asynchronous code

1.    Asynchronous Programming Model (APM)
2.    Event based Asynchronous Pattern (EAP)
3.    Task based asynchronous Pattern (TAP).

Asynchronous web pages can be written since ASP.NET 2.0 but it does not got much attention. Now it’s time to take advantage of this feature with available asynchronous models. In this post, We’ll use Asynchronous Programming Model (APM) to write the asynchronous web page. First let us just briefly discuss about asynchronous programming model (APM).

Asynchronous Programming Model (APM)

This asynchronous programming model is introduced with .NET 1.0 and it is also called IAsyncResult pattern. Here there are two methods are required, one starts with Begin keyword and another starts with End keyword so the name could be BeginOperationName and EndOperationName (This is just a naming convention). And once the BeginOperationName method is called, the thread is released and the task gets executed asynchronously, in the meantime and the released thread can pick some another task and EndOperationName method is called once the asynchronous task completes. BeginOperationName returns the type IAsyncResult. It can be pictorially shown as

APM ModelThere are few classes like FileStream (available under namespace System.IO.FileStream) exposes multiple type of Read methods like synchronous calls, it has Read() and for APM pattern it has BeginRead and EndRead as well. We can ourselves implement the same methods if we want to provide the similar feature to the class users.

Now let’s write our asynchronous web page using APM model. First, to make a page asynchronous, we need to set async=”true” in the page directive.

So in this web page, we are going to fetch the data from database and then bind it a GridView. So the code behind looks like

    public partial class AsynchronoususingAPM : System.Web.UI.Page
    {
        private SqlConnection sqlConnection;
        private SqlCommand command;
        private SqlDataReader sqlDataReader;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                AddOnPreRenderCompleteAsync(
                    new BeginEventHandler(BeginDataLoad),
                    new EndEventHandler(EndDataLoad)
                );
            }
        }

        IAsyncResult BeginDataLoad(object sender, EventArgs e, AsyncCallback asyncCallback, object state)
        {
            string connectionString = WebConfigurationManager.ConnectionStrings["AdventureWorksLT2008R2ConnectionString"].ConnectionString;
            sqlConnection = new SqlConnection(connectionString);
            sqlConnection.Open();
            command = new SqlCommand("SELECT Top 20 Title, FirstName, LastName, EmailAddress, Phone FROM SalesLT.Customer", sqlConnection);
            return command.BeginExecuteReader(asyncCallback, state);
        }

        void EndDataLoad(IAsyncResult asyncResult)
        {
            sqlDataReader = command.EndExecuteReader(asyncResult);
        }

        protected void Page_PreRenderComplete(object sender, EventArgs e)
        {
            gdCustomers.DataSource = sqlDataReader;
            gdCustomers.DataBind();
        }

        public override void Dispose()
        {
            if (sqlConnection != null)
                sqlConnection.Close();
            base.Dispose();
        }
   }

So here, if we see we have written to methods BeginDataLoad and EndDataLoad and binding that data Page_PreRenderComplete. So when we run this page, it looks likeAsyncPageLet’s discuss how it flows. When a user makes a request for this page, a thread is assigned to it from the thread pool. When the request reaches where it requires to fetch the data from the database, a database query is launched and current thread gets free and available to thread pool. When this query gets executed and the data comes to ASP.NET, ADO.NET requests a thread from thread pool and a thread is assigned to it from the thread pool which completes the request. It means while our database query was executing and the transporting the data from database to asp.net server, there was no thread involved and earlier executing thread was available to take another request.

Hope you guys have enjoyed this post. In the next post, We’ll write the asynchronous page using the next programming model.

Cheers,
Brij

Advertisement