ASP.NET MVC 4 - Implementing Asynchronous controller using .NET Framework 4.5

Most web developers know about ASP.NET’s request processing pipeline. An HTTP request is synchronously processed on a Thread which is grabbed from the ThreadPool. The Thread on which this request is processed is blocked from doing anything else like handling another incoming request.

This scenario can be really problematic for large number of concurrent requests. If the server is busy processing all these synchronous requests, the ‘Server Busy’ status code is send to the client.
To handle this effectively, in MVC, Asynchronous controllers can be used to process requests. The mechanism used by the asynchronous controller is that, the thread on which the request is put is freed and allocated back to the ThreadPool. When the response is ready, it is allocated on the other thread.

Async Controllers before .NET 4.5

The question arises here is that when to make use of the Asynchronous Controller, some considerations are as follows:
  • A Long running operation which is threat to the application performance because of thread blocking.
  • Operations making large transactions which utilize Network and IO resources.
  • Making calls to external WCF services


To implement Asynchronous Controllers in MVC3 and MVC 4 (without .NET Framework 4.5), it was necessary for the developer community to follow the below guidelines:
  • Async Action method e.g. (IndexAsync), this method starts asynchronous process and returns void.
  • Completed Action method e.g. (IndexCompleted), this is called when the asynchronous operation is completed and returns ActionResult.
The implementation is as follows:

public class EmployeeController : AsyncController
{
public void IndexAsync()
{
  AsyncManager.OutstandingOperations.Increment();
  MyRef.ServiceClient Proxy = new MyRef.ServiceClient();
  //Completed Events
  //When Complete, result will be received in the o/p Parameter
  Proxy.GetEmployeesCompleted += (sender, evt) =>
  {
   AsyncManager.Parameters["Employees"] = evt.Result;
   AsyncManager.OutstandingOperations.Decrement();  //Close Polling
  };
  Proxy.GetEmployeesAsync();  // Async method Call Initiated
}

public ActionResult IndexCompleted(IEnumerable<Employee> Employees)
{
  ViewData["Employees"] = Employees;
  return View(ViewData["Employees"]);
}
}

   
This implementation is a bit complex and it makes use of AsyncManager.OutstandingOperations, this is incremented before the operation is being started and Decremented when it is completed. Here the problem is as a developer, a lot of boilerplate has to be written. So how can we minimize it?

Async Controllers in .NET 4.5

In .NET Framework 4.5 we have two new keywords ‘async’ and ‘await’. So the above code can be easily reduced.

To implement the new Asynchronous Controller programming, I have created a WCF service which contains an ADO.NET EF. This service contains a method which return Employee’ List, the implementation is as below:

The DB Script:

USE [Company]
GO


CREATE TABLE [dbo].[EmployeeInfo](
    [EmpNo] [int] IDENTITY(1,1) NOT NULL,
    [EmpName] [varchar](50) NOT NULL,
    [Salary] [decimal](18, 0) NOT NULL,
    [DeptName] [varchar](50) NOT NULL,
    [Designation] [varchar](50) NOT NULL,
CONSTRAINT [PK_EmployeeInfo] PRIMARY KEY CLUSTERED
(
    [EmpNo] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO

   
ADO.NET EF

image001

The WCF Service

[ServiceContract]
public interface IService
{
[OperationContract]
List<EmployeeInfo> GetEmployees();
}


public class Service : IService
{
CompanyEntities objContext;
public Service()
{
  objContext = new CompanyEntities(); 
}
public List<EmployeeInfo> GetEmployees()
{
  var Emps = objContext.EmployeeInfoes.ToList();
  return Emps;
}
}

Consume the Service in MVC 4 project, make sure that you use target framework as .NET 4.5. (You can also use svcutil tool to generate the proxy.)

Add the new controller in the MVC project and add the following code:

public class EmployeeInfoController : AsyncController
{
ServiceClient Proxy;
public EmployeeInfoController()
{
  Proxy = new ServiceClient();
}
public async Task<ActionResult> Index()
{
  var Emps = await Proxy.GetEmployeesAsync();
  return View(Emps);
}
}


When we compare the above code of Index method with the code for Async operations explained earlier in the article, it’s really simple and maintainable. The ‘async’ and ‘await’ keywords takes care of the required asynchronous operation.

Conclusion

The async and await keywords help us write concise code when developing Asynchronous Controllers in ASP.NET MVC thus helping in building applications that can accept more requests than their synchronous counterparts.




About The Author

Mahesh Sabnis is a Microsoft MVP having over 18 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

1 comment:

Lev Bell said...

Model view controller is helpful for asp.net developer to create website easily.today most of company used mvc architecture in asp.net project.