In this article, we will see how to use Asynchronous Programming using Async and Await in ASP.NET 4.5 web forms. For demonstration purposes, we will create three different WCF Services which will fetch the Customers data, Total No. of orders and the Total Products respectively. Then we will use these services in our ASP.NET web site synchronously as well as asynchronously. We will calculate the time taken by an ASP.NET web site to call these services and find out the differences between these calls.

For this demonstration, I am using –

Windows Server 2012

Visual Studio 2012

SQL Server 2012

Let’s get started by creating three WCF Services with the name “CustomersService”, “OrdersService” and “ProductsService”. To create these service, we will first create a WCF Service using Visual Studio 2012. Open Visual Studio 2012. Click on File > New > Web Site and create a WCF Service with the name “NorthwindService” as shown below –

Once the WCF Service is ready, delete the default files, which are “Service.svc”, “IService.cs” and “Service.cs” files from the project.

Now right click the project and add a new Item to the project. Choose “ADO.NET Entity Data Model” and name it “Northwind”. As soon as you add the Entity data model, the IDE will display the Entity Data Model Wizard. Choose the Generate from database option in our first step and click on Next button. In this step, set up a connection to the Northwind database and save the connection string in Web.Config file. Click on “Next” button.

In this step, choose “Customers”, “Orders” and “Products” tables as shown below –

Click on “Finish” button. Now the wizard will display all the selected tables into our “Northwind.edmx” file.
Let’s add three WCF Services with the name “Cu
stomersService”, “OrdersService” and “ProductsService” respectively as shown below –

The above code is giving a call to the service synchronously. If you now run your “Default.aspx” page, you will see the records of Customers, total no. of records in Orders table and total no. of records in Products table. It will also show you the total execution time. In my case it took 12427 milliseconds.

Now let’s test the same code in terms of Asynchronous call. We will now modify the Page_Load event which will now give a call to the WCF services asynchronously as shown below –
First let’s add async attribute to our Page Directive as shown below –

In the above code, we are calling our WCF methods asynchronously. Each method returns Task<Type>. For example “TotalOrdersAsync()” method return us awaitable Task<int>.
Now we will have to get the actual result from the returned task by our service method. We can get the actual value by Result property of our Task<Type> as shown in the above code.

Task.WhenAll() method creates a task after completion of all the tasks supplied to it. We are passing all the three tasks to this method.