Use Asynchronous Methods in Asp.net MVC 4 with Examples

  Total Views : 1667
  Comments : 0
 
  Keywords : How to use asynchronous methods in asp.net mvc, Understand asynchronous methods in asp.net mvc with example, When to use asynchronous action methods in asp.net mvc with example

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

 

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

 

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

 

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

 

One of the good example for asynchronous programming is given by ASP.NET Program Manager was think asynchronous programming as Restaurant model in which 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. In similar way the asynchronous programming model works.

Synchronous Model

You can see in following image that there are no of users requesting and due to large IO or Database operation the processing is taking time that why thread pool is busy and thread pool is not able to handle these many user requests and all request got blocked.

 

synchronous programming model structure in asp.net mvc

Asynchronous Model

While in Asynchronous model when user request take too much time to process then that thread is detach and it is back in thread pool for handling other request means while long running process are still working.

 

Asynchronous model structure to handle requests in asp.net mvc

 

In .Net 4.5 Framework Microsoft have introduce 3 new keywords async, wait and Task. The Task is a class which comes under 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 relate operations

Create New Asp.Net MVC Application

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

 

create new asp.net mvc project from visual studio 2012

 

After that you will see new dialog will pop up 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 name as “Tutorial15” then finally click on OK button

 

Create new asynchronous asp.net mvc application

 

After naming and click on OK button now new dialog will pop up for selecting template in that Select Basic template and set view engine as Razor and we are not going to 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 as we told above now click OK button our asp.net mvc Project will be create like as shown below.

 

Asynchronous project structure to handle requests in asp.net mvc

 

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

Adding Web Service Reference to Project in Asp.Net MVC

We are going to add reference of weather report service provided by (www.webservicex.net ) and url will be http://www.webservicex.net/globalweather.asmx which is free to use. Check executing url in browser.

 

Accessing weather report web service in asp.net mvc

 

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

 

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

 

For adding reference just Right Click on Project then 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 name Add Service Reference will pop up. After that just add Address: http://www.webservicex.net/globalweather.asmx and click on Go button after that you will find similar view as shown below of Add Service Reference. Now last thing to do is to change Namespace ServiceReference1 to GetCities and Click on OK button.

 

adding weather report service reference in asp.net mvc application

 

After clicking on 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 controller just right click on Controller folder then select Add from list and inside that select controller.

 

add new controller in asp.net mvc application

 

After selecting controller a new dialog will pop up with 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 Empty MVC controller. Finally click on Add button to create HomeController. After adding controller that will contain code like as shown below.

 

Controller with default code in asp.net mvc application

 

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

 

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

 

Below you can see we created simple method which return 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 foreach loop we added these cities to list of string 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 list of cities from service now let’s call this method in (GetCitiesByCountrySync) Action Method and then assign it to local variable and return list. Following is the way of calling 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 Just right click inside Controller Action Method (GetCitiesByCountrySync) then select option Add View.

 

add view to controller in asp.net mvc application

 

After selecting Add View option a New Wizard will pop up with Name (Add View). It will have 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 required options click on Add button. A view will be created inside Views folder and in that we will have folder with name of controller inside that our view will be placed.

 

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

 

<h2>List of Cities</h2>

 

@foreach (var item in Model)

{

@item

<br/>

}

After writing code for displaying list of Cities on View now we are going Save and Run our Application and have look in browser how it performs.

 

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

 

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

Implementing Asynchronous Methods in Asp.Net MVC

First thing to do is adding async keyword to Action Method. If we use async Keyword in Method then 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 are going to add another Action Method in Home Controller with name GetCitiesByCountryAsync.

 

public ActionResult GetCitiesByCountryAsync() // Asynchronous Action Method

{

return View();

}

After adding Action Method let's add Async keyword to this Action Method. As we learned when we use async keyword then that method must also have await keyword in further step we will learn how to add await keyword to this Action Method.

 

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

{

return View();

}

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

 

public Task<List<string>> GetCitiesAsync()

{

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

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

XmlDocument xmlDoc = newXmlDocument();

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 are going to call GetCitiesAsync method in Action Method GetCitiesByCountryAsync and GetCitiesAsync Method will return list of string (Name of cities) and we assign this to local variable (List<string> listofcities) and use await keyword here to tell that wait until method GetCitiesAsync get complete.

 

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

 

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

{

List<string> listofcities = await GetCitiesAsync();

return View(listofcities);

}

After completion of adding GetCitiesByCountryAsync action method now let’s add View. For adding view just right click inside controller action method (GetCitiesByCountryAsync) then select option Add View like as shown below.

 

Add view to asynchronous method in asp.net mvc application

After selecting Add View option a New Wizard will pop up with Name (Add View). It will have 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 required options finally click on Add button. After that a view will be created inside Views folder and in that we will have folder with name of controller inside that our view will be created.

 

Open the view which we created that will be blank let’s display list of cities on view for that we need to add Action Method which is returning list of cities. On view we are going to add following code to display 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 list of Cities on view now we are going Save and Run our Application and have look in 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 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 mean while 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. 

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User