Working with Asynchronous Operations in ASP.NET 4.5 Web Forms

Introduction

Asynchronously running code can improve the overall performance and responsiveness of your web application. In ASP.NET 4.5 web forms applications you can register asynchronous methods with the page framework. The ASP.NET page framework and .NET 4.5 asynchronous programming support then executes the operations in asynchronous fashion. This article shows how this can be done.

NOTE: This article discusses how asynchronous operations can be used in ASP.NET web forms applications. Read Working with Asynchronous Operations in ASP.NET MVC to learn how asynchronous operations can be programed in ASP.NET MVC applications.

Example Scenario

Consider that you have a web application that needs to call two ASP.NET Web API services namely Customer and Product. These services return Customer and Product data from the Northwind database respectively. Now, assume that each of these services take 5 seconds to complete the data retrieval operation. If you use synchronous mode for calling these services then the total time taken will be 10 seconds. Because the execution will happen sequentially - first Customer service will complete and then Product service will complete.

On the other hand if you invoke these services in asynchronous fashion, the service operations won't block the caller thread. The Customer service will be invoked and control will be immediately returned to the caller. The caller thread will then proceed to invoke the Product service. So, two operations will be invoked in parallel. In this case the total time taken for completing both of the operations will be the time taken by the longest of the operations (5 seconds in this case).

Async, Await, Task and RegisterAsyncTask

Before developing web forms applications that execute asynchronous operations you need to understand a few basic terms involved in the process.

A task is an operation that is to be executed in asynchronous fashion. Such an operation is programmatically represented by the Task class from System.Threading.Tasks namespace.

When an asynchronous operation begins, the caller thread can continue its work further. However, the caller thread must wait at some point of time for the asynchronous operation to complete. The await keyword invokes an asynchronous operation and waits for it to complete.

The async modifier is applied to a method that is to be invoked asynchronously. Such an asynchronous method typically returns a Task object and has at least one await call inside it.

Just to understand how async, await and task are used at code level, consider the following piece of code:

public async Task<MyObject> MyMethodAsync()
{
  MyObject data = await service.GetDataAsync();
  //other operations on data go here
  return data;
}

Here, method MyMethodAsync() is marked with async modifier. By convention, asynchronous method names end with "Async". The MyMethodAsync() returns MyObject wrapped inside a Task instance. Inside the method a remote service is invoked using GetDataAsync(). Since MyMethodAsync() needs to return data retrieved from the service, the await keyword is used to wait till the GetDataAsync() method returns. Once GetDataAsync() returns the execution is resumed and further code is executed. The data is finally returned to the caller.

NOTE:
For a detailed understanding of async, await and Task refer to MSDN dicumentation. Here, these terms are discussed only for giving a basic understanding of the respective keywords.

ASP.NET page framework provides a method - RegisterAsyncTask() - that registers an asynchronous task with the page framework. Tasks registered using the RegisterAsyncTask() method are invoked immediately after the PreRender event. The RegisterAsyncTask() method takes a parameter of type PageAsyncTask. The PageAsyncTask object wraps the information about an asynchronous task registered with a page. The following piece of code shows how they are used:

protected void Page_Load(object sender, EventArgs e)
{
   PageAsyncTask task = new PageAsyncTask(MyMethod);
   RegisterAsyncTask(task);
}

Asynchronous Solution

Now that you are familiar with the basic concepts involved in utilizing asynchronous operations in a web forms application, let's create a sample application that puts this knowledge to use.

Begin by creating two projects - an empty web forms application and an ASP.NET MVC4 Web API application.

Add an Entity Framework Data Model for the Customers and Products tables of the Northwind database. Place the EF data model inside the Models folder.

Add an Entity Framework Data Model for the Customers and Products tables

Add an Entity Framework Data Model for the Customers and Products tables

Add two ApiController classes to the Web API project and name them as CustomerController and ProductController.

Add two ApiController classes

Add two ApiController classes

Then add Get() methods to both the ApiController classes as shown below:

public class CustomerController : ApiController
{
    public IEnumerable<Customer> Get()
    {
        Northwind db = new Northwind();
        var data = from item in db.Customers
                    select item;
        System.Threading.Thread.Sleep(5000);
        return data;
    }

}
public class ProductController : ApiController
{
    public IEnumerable<Product> Get()
    {
        Northwind db = new Northwind();
        var data = from item in db.Products
                    select item;
        System.Threading.Thread.Sleep(5000);
        return data;
    }

}

The Get() method of the CustomerController class selects all the Customer records from the Customers table whereas the Get() method of the ProductController class selects all the Product records. For the sake of testing, a delay of 5 seconds is introduced in each Get() method. The Get() methods return an IEnumerable collection of Customer and Product objects respectively.

Now, go to the web forms project and open the code behind file of the default web form. Here, you will write a couple of private methods that invoke the Web API developed previously. These methods are shown below:

public async Task<List<Customer>> InvokeCustomerService()
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync("http://localhost:49187/api/customer");
        string json= (await response.Content.ReadAsStringAsync());
        List<Customer> data = JsonConvert.DeserializeObject<List<Customer>>(json);
        return data;
    }
}

public async Task<List<Product>> InvokeProductService()
{
    using (HttpClient client = new HttpClient())
    {
        HttpResponseMessage response = await client.GetAsync("http://localhost:49187/api/product");
        string json = (await response.Content.ReadAsStringAsync());
        List<Product> data = JsonConvert.DeserializeObject<List<Product>>(json);
        return data;
    }
}

The InvokeCustomerService() method invokes the Customer Web API whereas InvokeProductService() method invokes Product Web API. Both the methods essentially use an HttpClient to get data from the respective Web API. Notice that both the methods have async modifier and return a Task instance that wraps the actual return type (List<Customer> and List<Product> respectively). The GetAsync() method of the HttpClient object is an asynchronous method. Call to the GetAsync() is marked using the await keyword so that further statements are executed only when GetAsync() returns. The GetAsync() method accepts a URL of the respective Web API. Make sure to change the port number as per your development setup. The GetAsync() method returns an HttpResponseMessage object. The actual data is then retrieved using ReadAsStringAsync() method of the Content property. The ReadAsStringAsync() will return data as a JSON string. This JSON data is converted into a .NET generic List using DeserializeObject() method of the JsonConvert class. The JsonConvert class comes from the Json.NET open source componenet. You can download Json.NET here.

The InvokeCustomerService() and InvokeProductService() methods are called inside another private method GetDataFromServicesAsync() as shown below:

private async Task GetDataFromServicesAsync()
{
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();

    var task1 = InvokeCustomerService();
    var task2 = InvokeProductService();

    await Task.WhenAll(task1, task2);

    List<Customer> data1 = task1.Result;
    List<Product> data2 = task2.Result;
            
    stopWatch.Stop();
    Label2.Text = string.Format("<h2>Retrieved {0} customers and {1} products in {2} seconds.</h2>", 
                                 data1.Count, data2.Count, stopWatch.Elapsed.TotalSeconds);
}

As shown above, GetDataFromServicesAsync() is also marked as async and returns a Task instance. Inside, a StopWatch class from System.Diagnostics namespace is used to find the time taken by both of the operations to complete. InvokeCustomerService() and InvokeProductService() methods are then called. The returned Task instance is stored in task1 and task2 variables respectively. The WhenAll() method of Task class creates another Task that completes when all the specified tasks are complete. In this case it creates a Task that completes after complition of task1 and task2. Actual data returned by the respective Web API is retrieved using the Result property of the respective Task objects. The time taken to complete the operation is measured by the StopWatch and is displayed in a Label.

The next step is to register GetDataFromServicesAsync() with the page framework. This is done using the RegisterAsyncTask() method as shown below:

protected void Page_Load(object sender, EventArgs e)
{
    RegisterAsyncTask(new PageAsyncTask(GetDataFromServicesAsync));
}

As you can see, Page_Load event handler registers an asynchronous task using RegisterAsyncTask() method. The RegisterAsyncTask() method accepts an instance of PageAsyncTask. The PageAsyncTask instance in turn wraps the GetDataFromServicesAsync() method created earlier.

The final step is to set Async attribute of the @Page directive to true:

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

The Aync attribute of the @Page directive indicates that this web form will be executed in asynchronous fashion. Web forms that use RegisterAsyncTask() method must set the Async attribute to true, otherwise an exception is raised at runtime.

This completes the application and you can test it by running the web forms application. The following figure shows a sample run of the web form:

A sample run of the web form

A sample run of the web form

Though the code doesn't show the synchronous execution of the Web API operations, for the sake of better understanding the above figure shows time taken for synchronous as well as asynchronous execution. Recollect that both the Get() methods sleep for 5 seconds and hence the synchronous execution takes approximately 10 seconds. However, the asynchronous execution takes approximately 5 seconds. As you can see the asynchronous operation improves the overall performance of the application.

Summary

Using async and await keywords you can create operations that run asynchronously. Such asynchronous tasks can be registered with the page framework using RegisterAsyncTask() method. Registered tasks run immediately after the PreRender event of the web form. Asynchronous operations can improve the overall performance and user responsiveness of a web application.



Related Articles

Comments

  • Wholesale Oakley Jury free shipping

    Posted by gufrotgvh on 06/24/2013 02:48pm

    Fake Oakleys For Sale ,The mixture of the very comprehensive eye care products on earth, Oakley sunglasses sale, a world free from the oldest and many well-known and quite a few respected health care brands. Denote explain the trend of Hollywood stars and fashion runways, in a few with the optical industry and consumer behavior statistical information is not displayed within the crowd which need a prescription. Oakleys Clearance ,Here is the soul of the trademark, the most notable from the quality and elegance of sunglasses for nearly all of the customer. The brand happens to be almost a normal category. Oakley is a trend, and present real world imitate two portions of sunglasses models, this is a well-known optical company Bausch & Lomb Bausch & Lomb brand. fake Oakley flak Jacket ,Oakley shade from the marketplace is an incredibly lots of needs around the world brand, Oakley sunglasses cheap brand from other a variety of good material. Oakley sunglasses, superiority and good design helps to reduce the sun's rays through your eyes, they are very popular exclusive appearance and fashion template. Sunglasses, cleaning fluid is quite particular, would like to know could it be seriously isn't correct to utilize paper or fingernails, since it is easily scratched sunglasses products. Women waiting to obtain with the utilization of previously they might want to purchase additional, nearly all period of a performance together because of their special handbags purses and handbags, for most months. You select an available range of sunglasses, these sunglasses are the activities arranged by polarization, the present style, special and restricted model. In a nutshell, not during the summer of Oakley sun screen lotion, approximately noon, at the Four Seasons, the encircling sea or sailing or at thin air winter sports. Oakley sunglasses would be the unique one lets you change a glasses, this is from your early 1980s, giving you a chance to have a very history of the resurrection in the original tool. Obviously people in addition to easy use in the outdoor needs of the greatest motorcycle Oakley shades UV 500 Oakley the scalpel sunglasses filtration to protect their vision. Most girls tend to be for example the development sari, related to the protection of your respective style are conscious of a brand image together with Oakley sunglasses cheap teenager understand that this manufacturer. Fortunately, Oakley sunglasses have different prices to meet up with their quality, but easier than trawling round shops to obtain online suppliers.

    Reply
  • the cheapest clarisonic pro with fuselage brush jumble sale in the ebay

    Posted by iouwanzi on 06/05/2013 06:35pm

    [url=http://www.miaclarisonicaustralia.org/]clarisonic australia[/url] If you don’t abuse your headphones, this shouldn’t be a problem. However, it’s worth noting since the headphone line after which these are styled—the Beats by Dr. Dre—doesn’t suffer from this issue. Simply put, the comparisons of the Beats line with the Zoro are only skin deep—they don’t sound similar and they aren’t built for the same type of usage.Despite the minor distortion at top volumes and the delicate nature of the drivers, the Noontec Zoro is a pretty solid audio performer at normal listening levels. The detachable cable adds a bit of value to the purchase, even if doesn’t feature an inline remote. [url=http://www.australiaclarisonic.com/]clarisonic australia[/url] Ligegyldigt om nogen efterspørgsel en ny hookup vedrørende personlig ansætte i dit hus samt med henblik på at venstre arm din nuværende lille vedrørende institution, dette er den meget specielle, der vil sikre en favorit BIII øretelefoner spørgende, Min ægtefælle og jeg gravede lidt dybere involveret med det sammen med min ægtefælle og jeg, din ml i allexpect en ny, netop hvad jeg lige kigger ind nedenfor besøgende i de mange standard fornødenheder. Sandheden er, jeg er bare planlægning for dig at adskille idéen sammen i dit tilfælde for at sige det kort sort. [url=http://www.australiaclarisonic.com/]clarisonic mia[/url] Det kan ikke være potentiel, at du er en total musik-freak, og du måske ikke tænker højtydende trådløse hovedtelefoner! Disse gadgets er de korrekte kammerater specielt inde du lytter til musik bestræbelser. Der er en række organisationer, først og fremmest de velkendte mærker, som Sony, Philips og Samsung osv., der tilfældigvis er i massiv organisering af elektroniske varer og tjenesteydelser og hovedtelefoner med Monstor Diddybeats White trådløse bestemmelser er en af dem. Du vil finde bestemte funktioner og faktorer, som har at blive alvorligt tages i betragtning, når 1 vælger denne fantastiske enhed. Målet er normalt at støde på en sund god kvalitet, der er helt sikkert virkelig vidunderlig og afslappende mod sindet også.

    Reply
  • Las planchas se usan ya en casi todos los desfiles de moda

    Posted by wanzilucky on 06/05/2013 06:33pm

    [url=http://ghd-espa-a.manifo.com/]GHD España[/url] Usando una combinación de la más alta de calor y ajuste de la velocidad y el botón de aire frío, el pelo se seca en menos de 5 minutos. El secador de pelo es ligero y de diseño ergonómico que se sienta muy bien en su mano, para no mencionar el hecho de que es más tranquilo y mi pelo se seca y rápidos. Me tomó un poco de tiempo para acostumbrarse a los botones en la parte posterior del secador de pelo – que fue diseñado para que sea accesible para los zurdos entre nosotros. [url=http://www.planchasespanaghdtop.net/]ghd españa[/url] Por lo visto la reina indiscutible de los foros es la GHD, pero mi duda es ¿es recomendable para un tipo de pelo como el mío una plancha sin regulador de temperatura? Mi pelo es muy fino, algo quebradizo y muy poroso. Para más inri llevo mechas con lo que tengo las puntas algo secas, pero las raices grasas y sin volumen. Tengo el pelo muuuy encrespado.Según dicen las GHD son las que más protegen el pelo pero, ¿también en un caso como el mío?Yo había pensado comprarme una con regulador de temperatura y utilizarla a 160 o 170º, pero las que he probado me siguen dejando el pelo encrespado y con las puntas secas, así que acabe devolviendolas (solac, rowenta, braun). [url=http://comprarsaleghd.webstarts.com/]planchas ghd baratas[/url] Pero déjame empezar diciendo, que nunca había utilizado un personal ghd antes de revisar tanto el Cloud Nine y el styler ghd IV. ¿Por qué? Porque nunca he entendido por qué la gente de la mesa a cabo los grandes dólares, cuando ésta llegó a estas pinzas calientes que aplanan el pelo. Prefiero gastar el dinero en ropa o zapatos. Al parecer, yo estaba equivocado al pensar con el cerebro de la moda, y estaba feliz de que se demuestre lo contrario, ya que mi cabello es naturalmente recto, pero de espesor, lo que hace un estilo difícil, si no quería que se acaba de ‘colgar’ sin fuerzas.

    Reply
  • Hvad der er godt for hovedtelefonerne

    Posted by wherewanzi on 06/05/2013 06:33pm

    [url=http://kbhretelefonerbillig.webstarts.com/]beats høretelefoner[/url] Derudover skal du få en dobbelt-strenget fly adapter sammen med en kvart tomme adapter til brug med dit hjem audio teknik. Endvidere vil en hård skal rejse sag med en tilsluttet karabiner, er beskyttet. Rekorder også komme som har en oprydning klud til at sikre, at de leder efter positive.Skulle du være bekymret for lyd og vises, vil du elske denne særlige laptop. Allerførste, vil denne pc giver dig ekstra at behandle din egen lyd resultat. Der er normalt sofistikerede antal audio muligheder, du vil aldrig afsløre sammen med andre pc’er.Søg efter gadgets er specielt designet til brug med elektriske mp3 enheder. I betragtning af at over-ear typer kan være store, søge efter versioner med neodymium varme. Næsten dine motiver udføre magneter synes vidunderlige, de har en tendens til at være mindre og lettere. [url=http://beatsbydrdredanmark.moonfruit.com/]beats by dre danmark[/url] Medmindre selvfølgelig, at du hellere træt, du aldrig kommer i seng, headsets i tillæg til et program, ferie kontorstol, nikkende, venter på dine vegne. Uanset om du er under metroen, workout, til hjemmet, hvor du arbejder af anden vej, for eksempel, giver næsten de fleste mennesker et headset hver eneste dag. Men når du burde “dele” enhver sang alle lytte, vil du have en persons Beats det alle. [url=http://beatsbydrdredanmark.moonfruit.com/]beats by dre danmark[/url] Kontakt de mennesker, der får dine ting og give dem konstruktiv klage omkring de spor, de gør. Dette vil få dig beundring, midler og en fremragende popularitet.Overlook sandheden om at skabe tiltalende ord, udvikle vidunderlige spor, samt at blande spor, så de virkelig blande o ‘så perfekt sammen for at hjælpe dig alligevel mærke til de forskellige aspekter af denne blanding.

    Reply
  • Software Eng.

    Posted by Nahu on 02/04/2013 07:29am

    What if I want to cancel(interrupt) the async process without completing the task?

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • A modern mobile IT strategy is no longer an option, it is an absolute business necessity. Today's most productive employees are not tied to a desk, an office, or a location. They are mobile. And your company's IT strategy has to be ready to support them with easy, reliable, 24/7 access to the business information they need, from anywhere in the world, across a broad range of communication devices. Here's how some of the nation's most progressive corporations are meeting the many needs of their mobile workers …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds