Joydip Kanjilal
Contributor

How to create asynchronous web pages in ASP.Net

how-to
Dec 18, 20174 mins
Small and Medium BusinessSoftware Development

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

abstract image of executives walking with skyline superimposed on bodies
Credit: 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.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author