"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Using Asynchronous Methods in ASP.NET 4.5

by Rick Anderson

This tutorial will teach you the basics of building an asynchronous ASP.NET Web Forms application using Visual Studio Express 2012 for Web, which is a free version of Microsoft Visual Studio. You can also use Visual Studio 2012. The following sections are included in this tutorial.

A complete sample is provided for this tutorial at
https://github.com/RickAndMSFT/Async-ASP.NET/ on the GitHub site.

ASP.NET 4.5 Web Pages in combination .NET 4.5 enables you to register asynchronous methods that return an object of type Task. The .NET Framework 4 introduced an asynchronous programming concept referred to as a Task and ASP.NET 4.5 supports Task. Tasks are represented by the Task type and related types in the System.Threading.Tasks namespace. The .NET Framework 4.5 builds on this asynchronous support with the await and async keywords that make working with Task objects much less complex than previous asynchronous approaches. The await keyword is syntactical shorthand for indicating that a piece of code should asynchronously wait on some other piece of code. The async keyword represents a hint that you can use to mark methods as task-based asynchronous methods. The combination of await, async, and the Task object makes it much easier for you to write asynchronous code in .NET 4.5. The new model for asynchronous methods is called the Task-based Asynchronous Pattern (TAP). This tutorial assumes you have some familiarity with asynchronous programing using await and async keywords and the Task namespace.

For more information on the using await and async keywords and the Task namespace, see the following references.

How Requests Are Processed by the Thread Pool

On the web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is busy while the request is being processed, and that thread cannot service another request.

This might not be a problem, because the thread pool can be made large enough to accommodate many busy threads. However, the number of threads in the thread pool is limited (the default maximum for .NET 4.5 is 5,000). In large applications with high concurrency of long-running requests, all available threads might be busy. This condition is known as thread starvation. When this condition is reached, the web server queues requests. If the request queue becomes full, the web server rejects requests with an HTTP 503 status (Server Too Busy). The CLR thread pool has limitations on new thread injections. If concurrency is bursty (that is, your web site can suddenly get a large number of requests) and all available request threads are busy because of backend calls with high latency, the limited thread injection rate can make your application respond very poorly. Additionally, each new thread added to the thread pool has overhead (such as 1 MB of stack memory). A web application using synchronous methods to service high latency calls where the thread pool grows to the .NET 4.5 default maximum of 5, 000 threads would consume approximately 5 GB more memory than an application able the service the same requests using asynchronous methods and only 50 threads. When you’re doing asynchronous work, you’re not always using a thread. For example, when you make an asynchronous web service request, ASP.NET will not be using any threads between the async method call and the await. Using the thread pool to service requests with high latency can lead to a large memory footprint and poor utilization of the server hardware.

Processing Asynchronous Requests

In web applications that see a large number of concurrent requests at start-up or has a bursty load (where concurrency increases suddenly), making web service calls asynchronous will increase the responsiveness of your application. An asynchronous request takes the same amount of time to process as a synchronous request. For example, if a request makes a web service call that requires two seconds to complete, the request takes two seconds whether it is performed synchronously or asynchronously. However, during an asynchronous call, a thread is not blocked from responding to other requests while it waits for the first request to complete. Therefore, asynchronous requests prevent request queuing and thread pool growth when there are many concurrent requests that invoke long-running operations.

Choosing Synchronous or Asynchronous Methods

This section lists guidelines for when to use synchronous or asynchronous Methods. These are just guidelines; examine each application individually to determine whether asynchronous methods help with performance.

In general, use synchronous methods for the following conditions:

In general, use asynchronous methods for the following conditions:

The downloadable sample shows how to use asynchronous methods effectively. The sample provided was designed to provide a simple demonstration of asynchronous programming in ASP.NET 4.5. The sample is not intended to be a reference architecture for asynchronous programming in ASP.NET. The sample program calls ASP.NET Web API methods which in turn call Task.Delay to simulate long-running web service calls. Most production applications will not show such obvious benefits to using asynchronous Methods.

Few applications require all methods to be asynchronous. Often, converting a few synchronous methods to asynchronous methods provides the best efficiency increase for the amount of work required.

The Sample Application

You can download the sample application from https://github.com/RickAndMSFT/Async-ASP.NET on the GitHub site. The repository consists of three projects:

The Gizmos Synchronous Page

The following code shows the Page_Load synchronous method that is used to display a list of gizmos. (For this article, a gizmo is a fictional mechanical device.)

[!code-csharpMain]

   1:  public partial class Gizmos : System.Web.UI.Page
   2:  {
   3:      protected void Page_Load(object sender, EventArgs e)
   4:      {
   5:          var gizmoService = new GizmoService();
   6:          GizmoGridView.DataSource = gizmoService.GetGizmos();
   7:          GizmoGridView.DataBind();
   8:      }
   9:  }

The following code shows the GetGizmos method of the gizmo service.

[!code-csharpMain]

   1:  public class GizmoService
   2:  {
   3:      public async Task<List<Gizmo>> GetGizmosAsync(
   4:          // Implementation removed.
   5:         
   6:      public List<Gizmo> GetGizmos()
   7:      {
   8:          var uri = Util.getServiceUri("Gizmos");
   9:          using (WebClient webClient = new WebClient())
  10:          {
  11:              return JsonConvert.DeserializeObject<List<Gizmo>>(
  12:                  webClient.DownloadString(uri)
  13:              );
  14:          }
  15:      }
  16:  }

The GizmoService GetGizmos method passes a URI to an ASP.NET Web API HTTP service which returns a list of gizmos data. The WebAPIpgw project contains the implementation of the Web API gizmos, widget and product controllers.
The following image shows the gizmos page from the sample project.

Gizmos
Gizmos

Creating an Asynchronous Gizmos Page

The sample uses the new async and await keywords (available in .NET 4.5 and Visual Studio 2012) to let the compiler be responsible for maintaining the complicated transformations necessary for asynchronous programming. The compiler lets you write code using the C#’s synchronous control flow constructs and the compiler automatically applies the transformations necessary to use callbacks in order to avoid blocking threads.

ASP.NET asynchronous pages must include the Page directive with the Async attribute set to “true”. The following code shows the Page directive with the Async attribute set to “true” for the GizmosAsync.aspx page.

[!code-aspxMain]

   1:  <%@ Page Async="true"  Language="C#" AutoEventWireup="true" 
   2:      CodeBehind="GizmosAsync.aspx.cs" Inherits="WebAppAsync.GizmosAsync" %>

The following code shows the Gizmos synchronous Page_Load method and the GizmosAsync asynchronous page. If your browser supports the HTML 5 <mark> element, you’ll see the changes in GizmosAsync in yellow highlight.

[!code-csharpMain]

   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:     var gizmoService = new GizmoService();
   4:     GizmoGridView.DataSource = gizmoService.GetGizmos();
   5:     GizmoGridView.DataBind();
   6:  }

The asynchronous version:

[!code-csharpMain]

   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:      RegisterAsyncTask(new PageAsyncTask(GetGizmosSvcAsync));
   4:  }
   5:   
   6:  private async Task GetGizmosSvcAsync()
   7:  {
   8:      var gizmoService = new GizmoService();
   9:      GizmosGridView.DataSource = await gizmoService.GetGizmosAsync();
  10:      GizmosGridView.DataBind();
  11:  }

The following changes were applied to allow the GizmosAsync page be asynchronous.

Inside of the GetGizmosSvcAsync method body another asynchronous method, GetGizmosAsync is called. GetGizmosAsync immediately returns a Task<List<Gizmo>> that will eventually complete when the data is available. Because you don’t want to do anything else until you have the gizmo data, the code awaits the task (using the await keyword). You can use the await keyword only in methods annotated with the async keyword.

The await keyword does not block the thread until the task is complete. It signs up the rest of the method as a callback on the task, and immediately returns. When the awaited task eventually completes, it will invoke that callback and thus resume the execution of the method right where it left off. For more information on using the await and async keywords and the Task namespace, see the async references.

The following code shows the GetGizmos and GetGizmosAsync methods.

[!code-csharpMain]

   1:  public List<Gizmo> GetGizmos()
   2:  {
   3:      var uri = Util.getServiceUri("Gizmos");
   4:      using (WebClient webClient = new WebClient())
   5:      {
   6:          return JsonConvert.DeserializeObject<List<Gizmo>>(
   7:              webClient.DownloadString(uri)
   8:          );
   9:      }
  10:  }

[!code-csharpMain]

   1:  public async Task<List<Gizmo>> GetGizmosAsync()
   2:  {
   3:      var uri = Util.getServiceUri("Gizmos");
   4:      using (HttpClient httpClient = new HttpClient())
   5:      {
   6:          var response = await httpClient.GetAsync(uri);
   7:          return (await response.Content.ReadAsAsync<List<Gizmo>>());
   8:      }
   9:  }

The asynchronous changes are similar to those made to the GizmosAsync above.

The following image shows the asynchronous gizmo view.

async
async

The browsers presentation of the gizmos data is identical to the view created by the synchronous call. The only difference is the asynchronous version may be more performant under heavy loads.

RegisterAsyncTask Notes

Methods hooked up with RegisterAsyncTask will run immediately after PreRender. You can also use async void page events directly, as shown in the following code:

[!code-csharpMain]

   1:  protected async void Page_Load(object sender, EventArgs e) {
   2:      await ...;
   3:      // do work
   4:  }

The downside to async void events is that developers no longer has full control over when events execute. For example, if both an .aspx and a .Master define Page_Load events and one or both of them are asynchronous, the order of execution can’t be guaranteed. The same indeterminiate order for non event handlers (such as async void Button_Click ) applies. For most developers this should be acceptable, but those who require full control over the order of execution should only use APIs like RegisterAsyncTask that consume methods which return a Task object.

Performing Multiple Operations in Parallel

Asynchronous Methods have a significant advantage over synchronous methods when an action must perform several independent operations. In the sample provided, the synchronous page PWG.aspx(for Products, Widgets and Gizmos) displays the results of three web service calls to get a list of products, widgets, and gizmos. The ASP.NET Web API project that provides these services uses Task.Delay to simulate latency or slow network calls. When the delay is set to 500 milliseconds, the asynchronous PWGasync.aspx page takes a little over 500 milliseconds to complete while the synchronous PWG version takes over 1,500 milliseconds. The synchronous PWG.aspx page is shown in the following code.

[!code-csharpMain]

   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:      Stopwatch stopWatch = new Stopwatch();
   4:      stopWatch.Start();
   5:   
   6:      var widgetService = new WidgetService();
   7:      var prodService = new ProductService();
   8:      var gizmoService = new GizmoService();
   9:   
  10:      var pwgVM = new ProdGizWidgetVM(
  11:          widgetService.GetWidgets(),
  12:          prodService.GetProducts(),
  13:          gizmoService.GetGizmos()
  14:         );
  15:      WidgetGridView.DataSource = pwgVM.widgetList;
  16:      WidgetGridView.DataBind();
  17:      ProductGridView.DataSource = pwgVM.prodList;
  18:      ProductGridView.DataBind();
  19:      GizmoGridView.DataSource = pwgVM.gizmoList;
  20:      GizmoGridView.DataBind();
  21:   
  22:      stopWatch.Stop();
  23:      ElapsedTimeLabel.Text = String.Format("Elapsed time: {0}", 
  24:          stopWatch.Elapsed.Milliseconds / 1000.0);
  25:  }

The asynchronous PWGasync code behind is shown below.

[!code-csharpMain]

   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:      Stopwatch stopWatch = new Stopwatch();
   4:      stopWatch.Start();
   5:      RegisterAsyncTask(new PageAsyncTask(GetPWGsrvAsync));
   6:      stopWatch.Stop();
   7:      ElapsedTimeLabel.Text = String.Format("Elapsed time: {0}",
   8:          stopWatch.Elapsed.Milliseconds / 1000.0);
   9:  }
  10:   
  11:  private async Task GetPWGsrvAsync()
  12:  {
  13:      var widgetService = new WidgetService();
  14:      var prodService = new ProductService();
  15:      var gizmoService = new GizmoService();
  16:   
  17:      var widgetTask = widgetService.GetWidgetsAsync();
  18:      var prodTask = prodService.GetProductsAsync();
  19:      var gizmoTask = gizmoService.GetGizmosAsync();
  20:   
  21:      await Task.WhenAll(widgetTask, prodTask, gizmoTask);
  22:   
  23:      var pwgVM = new ProdGizWidgetVM(
  24:         widgetTask.Result,
  25:         prodTask.Result,
  26:         gizmoTask.Result
  27:         );
  28:   
  29:      WidgetGridView.DataSource = pwgVM.widgetList;
  30:      WidgetGridView.DataBind();
  31:      ProductGridView.DataSource = pwgVM.prodList;
  32:      ProductGridView.DataBind();
  33:      GizmoGridView.DataSource = pwgVM.gizmoList;
  34:      GizmoGridView.DataBind();           
  35:  }

The following image shows the view returned from the asynchronous PWGasync.aspx page.

Using a Cancellation Token

Asynchronous Methods returning Taskare cancelable, that is they take a CancellationToken parameter when one is provided with the AsyncTimeout attribute of the Page directive. The following code shows the GizmosCancelAsync.aspx page with a timeout of on second.

[!code-aspxMain]

   1:  <%@ Page  Async="true"  AsyncTimeout="1" 
   2:      Language="C#" AutoEventWireup="true" 
   3:      CodeBehind="GizmosCancelAsync.aspx.cs" 
   4:      Inherits="WebAppAsync.GizmosCancelAsync" %>

The following code shows the GizmosCancelAsync.aspx.cs file.

[!code-csharpMain]

   1:  protected void Page_Load(object sender, EventArgs e)
   2:  {
   3:      RegisterAsyncTask(new PageAsyncTask(GetGizmosSvcCancelAsync));
   4:  }
   5:   
   6:  private async Task GetGizmosSvcCancelAsync(CancellationToken cancellationToken)
   7:  {
   8:      var gizmoService = new GizmoService();
   9:      var gizmoList = await gizmoService.GetGizmosAsync(cancellationToken);
  10:      GizmosGridView.DataSource = gizmoList;
  11:      GizmosGridView.DataBind();
  12:  }
  13:  private void Page_Error(object sender, EventArgs e)
  14:  {
  15:      Exception exc = Server.GetLastError();
  16:   
  17:      if (exc is TimeoutException)
  18:      {
  19:          // Pass the error on to the Timeout Error page
  20:          Server.Transfer("TimeoutErrorPage.aspx", true);
  21:      }
  22:  }

In the sample application provided, selecting the GizmosCancelAsync link calls the GizmosCancelAsync.aspx page and demonstrates the cancelation (by timing out) of the asynchronous call. Because the delay time is within a random range, you might need to refresh the page a couple times to get the time out error message.

Server Configuration for High Concurrency/High Latency Web Service Calls

To realize the benefits of an asynchronous web application, you might need to make some changes to the default server configuration. Keep the following in mind when configuring and stress testing your asynchronous web application.

Note in the images above, the .NET framework is listed as v4.0, even though the application pool is using .NET 4.5. To understand this discrepancy, see the following:

    - [.NET Versioning and Multi-Targeting - .NET 4.5 is an in-place upgrade to .NET 4.0](http://www.hanselman.com/blog/NETVersioningAndMultiTargetingNET45IsAnInplaceUpgradeToNET40.aspx)
    - [How to set an IIS Application or AppPool to use ASP.NET 3.5 rather than 2.0](http://www.hanselman.com/blog/HowToSetAnIISApplicationOrAppPoolToUseASPNET35RatherThan20.aspx)
    - [.NET Framework Versions and Dependencies](https://msdn.microsoft.com/en-us/library/bb822049(VS.110).aspx)

Contributors



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-forms/overview/performance-and-caching/using-asynchronous-methods-in-aspnet-45.htm
< THANKS ME>