How to create asynchronous web pages in ASP.Net

Take advantage of asynchronous web pages in ASP.Net to improve the responsiveness and scalability of your applications

How to create asynchronous web pages in ASP.Net
Thinkstock

Asynchronous programming allows you to execute tasks without holding up the execution flow or responsiveness of your application. By taking advantage of asynchronous methods to perform resource-intensive operations, you can increase the throughput of your application while at the same time ensuring that the user interface remains responsive.

Did you know you can leverage asynchronous webpages and asynchronous programming in ASP.Net to improve your application’s performance? In this article we’ll look at how we can build asynchronous webpages in ASP.Net. 

Asynchronous programming in ASP.Net

First we might ask why we need asynchrony in .Net. The .Net runtime maintains a pool of threads to service incoming requests. Each thread on the thread pool consumes 1MB of stack space. That may not sound like much, but if you have hundreds or thousands of threads serving high-latency requests, memory consumption could rise significantly.

Added to this, the thread pool has both a limited number of threads and a limited thread injection rate. So in applications with high concurrency, you can run out of threads—a problem known as thread starvation. When all of the threads available in the thread pool are busy, requests will be queued up by the web server. The web server may even reject requests if the request queue is already full.

Here is exactly where asynchronous programming comes to the rescue. When you have an asynchronous task in ASP.Net, the page lifecycle events will be executed as usual without having to wait for the asynchronous task to be completed.

An asynchronous webpage in ASP.Net should have the async attribute set in the page directive. All that you need to do is specify Page Async="true" in the markup code in your .aspx file and register the asynchronous methods that return a Task instance appropriately.

Create an ASP.Net web application

Now that we understand the concepts and what we intend to achieve, let’s get started. Open Visual Studio 2017 and click File -> New -> Project. Select Web as the project type and ASP.NET Web Application (.NET Framework) as the project template. Specify a name for the project and click OK. In the next window that pops up, specify Empty Project and click OK. 

That will create a new web application project with the name you specified. Next, select the web application project in the Solution Explorer window, add a new Web Form, and save it with a name.

Now, the first thing you should do is mark up the .aspx page with Async="true" as shown in the code snippet give below.

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

Register an asynchronous task in ASP.Net

The following code snippet illustrates how you can register an asynchronous task. Note that GetDataAsync is just a method that retrieves data from some data source, say by using plain ADO.Net. The RegisterAsyncTask method, which is available as part of the Page class, is used to register an asynchronous method with the webpage. The RegisterAsyncTask method takes PageAsyncTask as a parameter. Note that the methods registered using the RegisterAsyncTask method are executed immediately after the PreRender event for that webpage is fired.

public void Page_Load(object sender, EventArgs e)
        {
            RegisterAsyncTask(new PageAsyncTask(GetDataAsync));
        }

Below I show how the GetDataAsync method is used. Note that the word “async” is inserted before the method name just as a convention—it’s not a rule. The return type of this method is Task.

public async Task GetDataAsync()
        {
           //Some code
        }

Async and await in ASP.Net

Here is another example that illustrates how you can put asynchronous programming to work in ASP.Note. Note the use of the await keyword when calling the GetDataAsync method. Here await creates a callback on the GetDataAsync task and returns immediately. It does not block the thread until the task is complete. 

public void Page_Load(object sender, EventArgs e)
        {
            RegisterAsyncTask(new PageAsyncTask(async () =>
            {
                using (IDGAuthorsClient client = new
                     IDGAuthorsClient())
                {
                    var authors = await client.GetDataAsync();
                    dataGridAuthors.DataSource = authors;
                    dataGridAuthors.DataBind();
                }
            }));
        }

Support for asynchronous webpages were introduced way back in ASP.Net 2.0. However, with the introduction of the Task Parallel Library (TPL) with .NET 4.0, writing asynchronous methods became much easier than it was in those early days.

Copyright © 2017 IDG Communications, Inc.