Look at Asynchronous Page Processing in ASP.NET 4.5


In this blog, we will look into new Asynchronous Page Processing in ASP.NET 4.5 Web Forms. Asynchronous page processing will improve performance on long running tasks like file upload, database processing within your ASP.NET page. In ASP.NET, there is limited number of threads within the thread pool to serve your requests to a website. If all threads are busy doing complex processing, which takes so much time to finish the request.Iit will result in rejecting new requests to your website and makes your site unavailable to other users. In this scenario, asynchronous programming helps us to code long running tasks to free up assigned ASP.NET thread. Doing this, will free the thread and move it back to thread pool to serve new request. In Asynchronous Page Processing, the page will start processing in one thread from the thread pool and might complete processing in a different one, after the async processing completes.

Let’s have a look with an example. Create a new web application in VS 11 with name as AsyncDemo.

Now add a fileupload control, a button and async=”true” to Page directive for default.aspx as shown below:

 

Add below code under button1_click to upload a local file on box running VS:

 

 It will upload a local file to c:\uploads folder asynchronously. RegisterAsyncTask and PageAsyncTask were part of.NET 2.0. The await keyword is new from the .NET 4.5 asynchronous programming model and can be used together with the new Task Async methods like DownloadFileTaskAsync of WebClient.

The RegisterAsyncTask registers a new page asynchronous task to be executed in a different thread. It receives a lambda expression with the object (o), the action (a) and the cancelation token (ct).

The async keyword is one of the new keywords the .NET Framework 4.5 provides; it tells the compiler that this method contains asynchronous code.

The await keyword in the DownloadFileTaskAsync method call makes the execution of the task stop until the method has returned its value. ASP.NET will resume the execution of the method, automatically maintaining all the HTTP request original values.

Run the application and select a file and click “Upload Async” to upload it into c:\uploads folder asynchronously as shown below:

The thread ID before and after the asynchronous task is different. This is because asynchronous tasks run on a separate thread from ASP.NET thread pool. When the task completes, ASP.NET puts the task back in the queue and assigns any of the available threads.

Note: This blog is based on features of preview only, and is subject to change in later releases.

Skip to main content