Sunday, 11 November 2012

Asynchronous pages in ASP.NET 4.5

In my previous post, we discussed the importance of asynchrony in ASP.NET applications. Before that, I blogged about using asynchrony in C# 5 and calling WCF services asynchronously using features in C# 5. In this post, we will learn how to create an ASP.NET web forms page that performs some asynchronous operations.

To make a page asynchronous in earlier versions of ASP.NET, the page has to implement the interface IHttpAsyncHandler and define concrete definitions to all the methods declared in the interface. This takes considerable amount of time and effort to make the page asynchronous.

In ASP.NET 4.5, we can turn the execution of any operation asynchronous by using async and await keywords. Any new page added to an ASP.NET application is considered synchronous by default. We can change this by setting value of Async property of the Page directive to true. Once this property is set, we can use async and await keywords in any method in the code behind file.

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

This is because, performing asynchronous operations at wrong time may lead to some dangerous conditions on the server. By setting the Async attribute of the page, we are telling the server that, the current page is a safe place to perform async operations. Following is a sample page load event handler that calls a WCF service asynchronously and binds data to a GridView:
protected async void Page_Load(object sender, EventArgs e)
{
    var client = new DataServiceClient();
    var gettingCities = await client.GetCitiesAsync();
    gvCities.DataSource = gettingCities;
    gvCities.DataBind()                                                  
}

Following are the set of steps performed when ASP.NET detects the await keyword in the above event handler:
  • Continues executing other synchronous tasks of the life cycle event
  • Once the above step is finished, the underlying synchronization context fires up an event saying that an async operation is pending
  • ASP.NET waits asynchronously till the pending task is completed and then it continues executing the rest of the statements
  • With above step, the life cycle (page load in this case) event is over. The control goes ahead to the next life cycle event


There is another way to achieve this. It is shown in the following snippet:
protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(async () =>
    {
        var client = new DataServiceClient();
        var gettingCities = await client.GetCitiesAsync();
        gvCities.DataSource = gettingCities;
        gvCities.DataBind();
    }));                                                                                    
}

The advantage of performing async operation this way over what we did earlier is that, it registers an asynchronous handler with the page and now the execution is not dependent on the synchronization context. Execution of the statements in the PageAsyncTask passed in is not dependent on page the page life cycle event. So, ASP.NET will not wait asynchronously after executing rest of the logic in the life cycle event. It would rather continue execution with the next life cycle event handlers. Statements in the registered task are performed whenever the dependent operation is finished.

Note that, we used the async keyword with a lambda expression. It is legal in .NET 4.5, because lambda is meant to create a single cast delegate with an anonymous method. To make the method executable asynchronously, we can use async and await with lambda.

Further learning: Async in ASP.NET talk from AspConf 2012

Happy coding!

No comments:

Post a Comment

Note: only a member of this blog may post a comment.