Leveraging the Power of Asynchrony in ASP.NET

Asynchronous programming has had a lot of attention in the last couple of years and there are two key reasons for this: First it helps in providing a better user experience by not blocking the UI thread which avoids the hanging of the UI screen until the processing is done and second, it helps in scaling up the system drastically without adding any extra hardware.

But writing asynchronous code and managing the thread gracefully was a tedious task. But as the benefits are tremendous.. Read complete post on Infragistics blog

Advertisement

Asynchronous programming with async and await : explained

In one of my previous posts, I discussed about the synchronous and asynchronous programming model. We saw in details that how does it work in single and multi-threaded mode. This post is extension of that post and here we are going to discuss the two relatively new keyword async and await and how does that actually work. I got many questions around this so sharing it in details here. If you are not very clear about how synchronous and asynchronous programming works and how does it work in single and multi-threaded scenario then refer my previous post mentioned below.

Concurrency vs Multi-threading vs Asynchronous Programming : Explained

Continue reading

Writing Asynchronous Web Pages with ASP.NET- Part 3

This is third post in the series of Writing Asynchronous Web Pages with ASP.NET. In first post, We discussed briefly about various asynchronous patterns and wrote an asynchronous web Page using APM model. In second part, we used Event-based asynchronous pattern (EAP) and discussed it with a example. Please find the links of my earlier post below.

  1. Writing Asynchronous Web Pages with ASP.NET- Part 1
  2. Writing Asynchronous Web Pages with ASP.NET- Part 2

 

In this post, we are going to use another pattern. .NET 4.0 introduced Task Parallel Library (TPL), which simplified the way to write asynchronous code. Let’s briefly understand the TPL. It provides a method (as naming convention method name ends with async) which returns a Task (or Task<TResult>) .

Task represents an asynchronous operation which contains the Result once completes. After getting the task, we can do some other activity and can keep checking the status of the Task. Once it completes, read the result from the Task.

We can provide an asynchronous method in our class that provides an async method that returns a task as

public class MyCustomClass
{
    public Task<int> ReadAsync(byte[] buffer, int offeset, int count);
}

Task actually internally uses Thread Pool and a thread is allocated to the task using thread pool to complete the task but all this complexity is hidden from the user and .NET itself lays down the required infrastructure for this.

Now, scores of classes in .NET libraries supports this pattern and we can make use of that.

.NET4.5 made our life much easier by introducing to keywords async and await which allows us to write the asynchronous code in a synchronous way. All the other required basic activities like context switching etc are taken care by the .NET framework for us. These keywords are provided over Task Parallel Library  that got introduced in .NET 4.0. Writing asynchronous activities with these keywords are highly optimized, performance oriented and make best use of TPL.

Now let’s use this pattern and write another asynchronous page. So in this examples, I am using a WCF service that returns a list of Employees and that is getting displayed on the web page. So our Page_Load method could look like

protected async void Page_Load(object sender, EventArgs e)
{
    WcfService.Service1Client client = new Service1Client();

    var customers = await client.GetEmployeesAsync();
    gdCustomers.DataSource = customers;
    gdCustomers.DataBind();
}

So as we see here that my service supports the TPL, async and await keywords based asynchronous pattern.

In page life cycle, when Page_load gets fired, ASP.NET finds it async and when it reaches to await, it releases the current thread and a new thread is picked from the thread pool to continue the activity and the call the web service took place asynchronously. Once the data returns from service, the same UI thread is assigned to execute further.
But there is better way to use async and await in web page. This has an issue as well and execute the code in synchronous mode . As we know our page life cycle has a set of events that gets fired in a predefined order and next event will be fired only when the last event completes. So if we use the above way of async Page_Load, this event will be fired during page life cycle event once it reaches to async, current thread gets free and a another thread got assigned to complete the task asynchronously, but the ASP.NET cannot execute the next event in life cycle because Page_Load has not been completed yet. And underlying synchronization context waits till the asynchronous activity completes. Then only the next event of page lifecycle will be fired which makes the whole process in synchronous mode only.

So to avoid it, there is a better is available. So the new way uses ASP.NET method RegisterAsyncTask which takes PageAsyncTask as a parameter. So let’s write the code then we’ll discuss that How does it work?

protected void Page_Load(object sender, EventArgs e)
        {
            RegisterAsyncTask(new PageAsyncTask(async () =>
            {
                using (Service1Client client = new Service1Client())
                {

                    var customers = await client.GetEmployeesAsync();
                    gdCustomers.DataSource = customers;
                    gdCustomers.DataBind();
                }
            }));
        }

Here, we have register a delegate using method RegisterAsyncTask at Page_Load. It does not fire the event while running the Page_Load event. Here it just register an event and tell the ASP.NET to execute it. Now as we have already marked page as async, ASP.NET itself decides the best time to execute it asynchronously and Page Life cycle events gets fired as usual without waiting for the async task to complete. This is very useful in the scenarios where we want to run multiple asynchronous tasks. Multiple tasks can run parallel if required. So now we have given the liberty to ASP.NET to execute this task asynchronously rather than waiting for the async task to get it completed then fire the next page life cycle events.

Hope you have enjoyed the post.

Cheers,
Brij

Writing asynchronous HTTP Module in ASP.NET 4.5

Today again, I am going to discuss , one of the new features that got enhanced in ASP.NET 4.5. And It is Asynchronous HTTP Module . And it’s going to be very useful if used meticulously.

First Just to give a brief Idea, why Asynchronous HTTPModules are important ?

As we all know, web is stateless. A Web page is created from scratch every time whenever it is posted back to the server. In traditional web programming, all the information within the page and control gets wiped off on every postback. Every request in ASP.NET goes through a series of events.

Every request is served by am HTTP handler and it goes a series of HTTPModules (HTTPPipeline) which can be read, update the request. A lot of features of ASP.NET like Authentication, Authorization, Session etc are implemented as HTTP Module in ASP.NET. Let’s have a view on the Request Processing

ASP.NET Request Processing : HTTPPipeline and HTTPHandler


Now as you can see the request is assigned to a thread T1 from the available threads is thread pool. And the request is passed through several HTTPModules and finally served my HTTPHandler and response is send back with the same thread (T1).

During the entire processing, same thread is engaged in serving  the same request and cannot be used by any another request till request processing completes.  During the request processing if any HTTPModules depends on some entities like I/O based operations, web services, Databases queries etc then it takes long to complete which makes the thread busy for long which makes asp.net thread will not do anything during that duration and will be useless.  In this kind of scenarios the throughput goes down rapidly.

In the above scenario, synchronous HTTPModule can degrade the site performance a lot. So if we can make  HTTPModules as asynchronous  that can increase the through put a lot.  In asynchronous mode, ASP.NET thread get released as soon as the control get passed to another component/module, it does not wait. And the thread becomes available in thread pool and can be used to serve another request. When the component completes its assigned task then it got assigned to new ASP.NET thread which completes the request. The flow can be graphically presented as

Working of an asynchronous HTTPModule

In the above picture, An asp.net thread T1 is assigned from threadpool to server the request. When the control got passed to File System to log message, asp.net thread got  released and when essage logging got completed, control passed to asp.net and it is assigned to another thread say T2 from thread pool.
In .NET Framework 4.o, there was some major enhancement made for asynchronous programming model. Any asynchronous operation is represents a Task and it comes under the namespace System.Threading.Tasks.Task.

In .NET 4.5, there are some new operator and keyword introduced that makes the life easy for implement Asynchronous feature. One is async keyword and await operator.

These two enables us to write the asynchronous code is similar fashion as we write for synchronous mode.

And these features can be easily used while writing HTTPModules and HTTPHandlers. We’ll be using these enhancements in writing our custom asynchronous HTTPModule.

In my sample as depicted in image, I am creating a module that writes some log messages in a text file for every request made.

So to create a Custom HTTPModule, Create a class library project. And create a class  say named LogModule which implements IHttpModule. For this you need to add a reference of Assembly System.Web.

LogModule would contains the methods discussed below.

We need to implement two methods Init and Dispose that are part of IHTTPModule interface.

Here first , I have written an asynchronous method that actually reads the information from the request and writes in the log file asynchronously . For this I have used WriteAsync of FileStream

private async Task WriteLogmessages(object sender, EventArgs e)
{
	HttpApplication app = (HttpApplication)sender;
        DateTime time = DateTime.Now;

        string line = String.Format(
        "{0,10:d}    {1,11:T}    {2, 32}   {3}\r\n",
        time, time,
        app.Request.UserHostAddress,
        app.Request.Url);
        using (_file = new FileStream(
            HttpContext.Current.Server.MapPath(
              "~/App_Data/RequestLog.txt"),
            FileMode.OpenOrCreate, FileAccess.Write,
            FileShare.Write, 1024, true))
        {
            line = line + "  ," + threaddetails;
            byte[] output = Encoding.ASCII.GetBytes(line);

            _file.Seek(_position, SeekOrigin.Begin);
            _position += output.Length;
            await _file.WriteAsync(output, 0, output.Length);
        }

}

Here you can see the await key word, what it means..

As per msdn “An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.

await is used with some asynchronous method that returns task and is used suspend the execution of the method until the task completes and control is returned back to the caller to execute further. await should be used with the last expression of any code block.

And Init method would be like

public void Init(HttpApplication context)
{
        // It wraps the Task-based method
        EventHandlerTaskAsyncHelper asyncHelper =
           new EventHandlerTaskAsyncHelper(WriteLogmessages);

        //asyncHelper's BeginEventHandler and EndEventHandler eventhandler that is used
        //as Begin and End methods for Asynchronous HTTP modules
        context.AddOnPostAuthorizeRequestAsync(
        asyncHelper.BeginEventHandler, asyncHelper.EndEventHandler);

}

So apart from above these methods, we need to implement the dispose method.

Now compile your class library and use the reference in your ASP.NET website . Now as you must be knowing that we need to need to add the entry in the config file. So it’ll be as

<system.webServer>
<modules>
<add name="MyCustomHTTPModule" type="MyCustomHTTPModule.LogModule, MyCustomHTTPModule"/>
</modules>
</system.webServer>

Now when you run your application, you will see the logs are created in a text file in App_Data folder as mentioned path in the code.

Hope you all have liked this new feature.