Use Asynchronous Methods in Asp.net MVC 4 with Examples

In today's world, most of the application work based on Synchronous programming in which the client sent a request to the server and server process the task and sent a response back to the client. 

 

The synchronous controllers work well for the concept, but it cannot handle the long-running processes. When a user sends a request to the server, ASP.NET will provide one of the threads from the thread pool to handle the request. If the request process takes less time to complete, it provides fast output to the client, but when requests take more time for the process, it will block the thread, and this thread will not be available to another request to handle.

 

If such large requests are sent from users, and all are long-running processes, then the server will be blocked, then there will be no thread to handle this request, and the server will fire an Error message. “Server too Busy” to handle this, we need to use Asynchronous programming.

 

In Asynchronous programming, handling requests is when the user sends a request to the server will provide one of the threads from the thread pool to handle the request if this request is long-running. This thread will come back to the thread pool, and your request will keep on the process until it completes; meanwhile, the thread which came back in the thread pool will handle a new request. As the long-running process has completed, then the ASP.NET will allocate a new ideal thread from the thread pool to complete this request, and this way, Asynchronous programming will work.

 

ASP.NET Program Manager gives one good example of asynchronous programming. It was thought of asynchronous programming as a Restaurant model. A waiter comes to a table, takes your request, then goes after food is prepared he comes back and then serves you food then he goes back. Similarly, the asynchronous programming model works.

Synchronous Model

You can see in the following image that many users are requesting, and due to large IO or Database operation, the process will take time, and the thread pool is busy. The thread pool is not able to handle these many user requests, and all requests got blocked.

 

synchronous programming model structure in asp.net mvc

Asynchronous Model

In the Asynchronous model, when a user request takes too much time to process, that thread is detached, and it is back in the thread pool for handling other request means while the long-running process is still working.

 

Asynchronous model structure to handle requests in asp.net mvc

 

In .Net 4.5 Framework Microsoft has introduced 3 new keywords async, await, and Task. The Task is a class that comes under the namespace System.Threading.Tasks.

 

Now we had lots of theory, let’s do some Practical. Here we will learn how to use async wait and Task in asp.net mvc project and how it is different from traditional methods (Synchronous).

 

When to use Asynchronous methods in asp.net mvc

 

   1) During Long-running operations

   2) Web services related operations

Create New Asp.Net MVC Application

Let's start with creating a new asp.net MVC 4 application for that Open visual studio à Go to File à Select New à Select Project.

 

create new asp.net mvc project from visual studio 2012

 

After that, you will see a new dialog for selecting your Template and Project type. From Templates, select Visual C# à inside that select Web and then project type select ASP.NET MVC 4 Web Application, and here we are giving the name "Tutorial15” then finally click on OK button.

 

Create new asynchronous asp.net mvc application

 

After naming and click on the OK button, a new dialog will pop up for selecting a template in that Select Basic template and set view engine as Razor. We will not create Unit testing for this project; hence, do not check this option and finally click OK like as shown below.

 

select basic template to create new application in asp.net mvc

 

After selecting all options, click the OK button. Our asp.net MVC Project will be created, as shown below.

 

Asynchronous project structure to handle requests in asp.net mvc

 

After completing creating our project, let’s add a web service reference to our Project.

Adding Web Service Reference to Project in Asp.Net MVC

We will add a reference to the weather report service provided by (www.webservicex.net ), and the URL will be http://www.webservicex.net/globalweather.asmx that is free to use. Check to execute the URL in the browser.

 

Accessing weather report web service in asp.net mvc

 

Following is data of Cities based on the country by Invoking the GetCitiesByCountry method from service.

 

xml data returned by weather report webservice in asp.net mvc

 

To add a reference, right-click on the Project, select Add Service Reference like as shown below.

 

Adding web service reference in asp.net mvc application

 

After selecting Add Service Reference, a New dialog with the name Add Service Reference will pop up. After that, add Address: http://www.webservicex.net/globalweather.asmx and click on the Go button. After that, you will find a similar view as shown below of Add Service Reference. Now the last thing to do is to change Namespace ServiceReference1 to GetCities and Click on the OK button.

 

adding weather report service reference in asp.net mvc application

 

After clicking on the ok button, you will see GetCities Service Reference added to your Project.

 

After adding weather report service in asp.net mvc application

 

After completion of adding GetCities Service Reference, now let’s Add Controller.

Add New Controller in Asp.Net MVC

To add a controller, right-click on the Controller folder, select Add from the list, and inside that select controller.

 

add new controller in asp.net mvc application

 

After selecting the controller, a new dialog will pop up with the name Add Controller.

 

Give name to controller and select template as empty mvc controller in asp.net mvc application

 

Now let’s name a Controller to HomeController. In Template, we are going to select the Empty MVC controller. Finally, click on the Add button to create HomeController. After adding a controller that will contain code like as shown below.

 

Controller with default code in asp.net mvc application

 

After adding HomeController, you will see the Index Action Method created by default. Now let’s add New Action Method with Name (GetCitiesByCountrySync). This will be a Synchronous Method.

 

After adding Action Method, we will create another simple method to consume web service (GetCitiesSync) and return a list of string which are list Cities name.

 

Below you can see we created a simple method that returns a List of string inside this method we are consuming web service and this service return XML for manipulating this we used XmlDocument. After that, using the foreach loop, we added these cities to the string list and returned.

 

public List<string> GetCitiesSync()

{

GetCities.GlobalWeather list = new GetCities.GlobalWeather();

string Data = list.GetCitiesByCountry("India");

 

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.LoadXml(Data);

 

XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("//Table");

List<string> Listcity = new List<string>();

foreach (XmlNode node in nodes)

{

Listcity.Add(node["City"].InnerText);

}

return Listcity;

}

After getting a list of cities from the service, let’s call this method in (GetCitiesByCountrySync) Action Method and then assign it to a local variable and return list. Following is the way of calling the GetCitiesSync() Method in Action Method.

 

public ActionResult GetCitiesByCountrySync() // Synchronous Method

{

List<string> list = GetCitiesSync();

return View(list);

}

After calling GetCitiesSync() method in GetCitiesByCountrySync Action Method now let’s add view to this Action Method.

Adding View (GetCitiesByCountrySync) in Asp.net MVC

For Adding View right-click inside Controller Action Method (GetCitiesByCountrySync) then select option Add View.

 

add view to controller in asp.net mvc application

 

After selecting the Add View option, a New Wizard will pop up with Name (Add View). The View Name same as Action Method inside which you right-click to add View. In this example, we are not going to select any model class.

 

Give name to synchronous method in asp.net mvc application

 

After selecting the required options, click on the Add button. A view will be created inside the Views folder, and in that, we will have a folder with the name of the controller inside that our view will be placed.

 

If we open the view which we added in edit mode, then it will blank. Let’s display a list of cities on view for that our Action Method should return a list of cities. On the view, we are going to add the following code to display a list of cities.

 

<h2>List of Cities</h2>

 

@foreach (var item in Model)

{

@item

<br/>

}

After writing code for displaying a list of Cities on View, we will save and Run our Application and have looked in the browser how it performs.

 

Showing list of cities in asp.net mvc using synchronous action method

 

Till now everything, we did it in a Synchronous way. Let’s do this in an Asynchronous way.

Implementing Asynchronous Methods in Asp.Net MVC

The first thing to do is to add the async keyword to Action Method. If we use the async Keyword in Method, the Method must also use await Keyword. The return type of an async method must be void, Task or Task<T> we have used Task<T> in Action Method. 

 

For implementing Asynchronous Methods, we will add another Action Method in Home Controller with the name GetCitiesByCountryAsync.

 

public ActionResult GetCitiesByCountryAsync() // Asynchronous Action Method

{

return View();

}

After adding the Action, Method, let's add the Async keyword to this Action Method. When we use the async keyword, that method must also have the await keyword. In a further step, we will learn how to add the await keyword to this Action Method.

 

public async Task<ActionResult> GetCitiesByCountryAsync() // Asynchronous Action Method

{

return View();

}

After adding the Action Method and Async keyword to Action Method, we will create another simple Method with the name (GetCitiesAsync). In this method, we will consume web service (GetCitiesAsync) and return a list of cities. As this method returns a Task list of string for that we are not using any async and await keyword here, we will return Task [Task.FromResult(Listcity);]

 

public Task<List<string>> GetCitiesAsync()

{

GetCities.GlobalWeather list = new GetCities.GlobalWeather();

string Data = list.GetCitiesByCountry("India");

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.LoadXml(Data);

XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("//Table");

List<string> Listcity = new List<string>();

foreach (XmlNode node in nodes)

{

Listcity.Add(node["City"].InnerText);

}

return Task.FromResult(Listcity);

}

Now we will call the GetCitiesAsync method in Action Method GetCitiesByCountryAsync, and the GetCitiesAsync method will return a list of string (Name of cities). We assign this to a local variable (List<string> listofcities) and use the await keyword to tell that wait until method GetCitiesAsync gets complete.

 

The await operator is applied to a task in an asynchronous method to suspend the execution method until the awaited task completes. Now let’s use the await keyword.

 

public async Task<ActionResult> GetCitiesByCountryAsync() // Asynchronous Action Method

{

List<string> listofcities = await GetCitiesAsync();

return View(listofcities);

}

After completion of adding the GetCitiesByCountryAsync action method, let’s add View. To add view, right-click inside controller action method (GetCitiesByCountryAsync), select option Add View like as shown below.

 

Add view to asynchronous method in asp.net mvc application

After selecting the Add View option, a New Wizard will pop up with Name (Add View). It will have a view name same as Action Method inside which you right-click to add View. In this example, we are not going to use any model class.

 

Adding new view to action method in controller in asp.net mvc

 

After selecting the required options, click on the Add button. After that, a new view will be created inside the Views folder, and in that, we will have a folder with the name of the controller inside that our view will be created.

 

Open the view which we created that will be blank. Let’s display a list of cities on view for that we need to add Action Method, which is returning a list of cities. On view, we are going to add the following code to display the list of cities.

 

<h2>List of Cities</h2>

 

@foreach (var item in Model)

{

@item

<br/>

}

Our complete Homecontroller will be like, as shown below.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading;

using System.Threading.Tasks;

using System.Web;

using System.Web.Mvc;

using System.Xml;

 

namespace Tutorial15.Controllers

{

public class HomeController : Controller

{

public ActionResult GetCitiesByCountrySync() // Synchronous Action Method

{

List<string> list = GetCitiesSync();

return View(list);

}

public List<string> GetCitiesSync() // Synchronous Method

{

GetCities.GlobalWeather list = new GetCities.GlobalWeather();

string Data = list.GetCitiesByCountry("India");

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.LoadXml(Data);

XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("//Table");

List<string> Listcity = new List<string>();

foreach (XmlNode node in nodes)

{

Listcity.Add(node["City"].InnerText);

}

return Listcity;

}

public async Task<ActionResult> GetCitiesByCountryAsync() // Asynchronous Action Method

{

List<string> listofcities = await GetCitiesAsync();

return View(listofcities);

}

public Task<List<string>> GetCitiesAsync()  // Asynchronous Method

{

GetCities.GlobalWeather list = new GetCities.GlobalWeather();

string Data = list.GetCitiesByCountry("India");

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.LoadXml(Data);

XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("//Table");

List<string> Listcity = new List<string>();

foreach (XmlNode node in nodes)

{

Listcity.Add(node["City"].InnerText);

}

Thread.Sleep(100000);

return Task.FromResult(Listcity);

}

}}

After writing code for displaying the list of Cities on view, we will save and Run our Application and look in the browser how this performs.

 

Showing cities using asynchronous method in asp.net mvc application

Accessing both Synchronous and Asynchronous Methods

As you can see, both Synchronous and Asynchronous Methods running simultaneously, but the async method we suspended for 1 minute (We used Thread.Sleep(100000); for making method to wait till 1 minute [you can see code snippet of HomeController for details]) and meanwhile we can access Synchronous Method.

 

Accessing both Synchronous and Asynchronous Methods simultaneously in asp.net mvc with example

 

This is how we can use asynchronous action methods in our applications.