Saturday, 17 November 2012

Asynchronous controller actions in ASP.NET MVC 4

In this post, let’s continue our discussion on asynchronous programming in .NET 4.5 with ASP.NET MVC4. We will see how to create asynchronous controller actions in ASP.NET MVC 4.

 As in case of pages and handlers ASP.NET web forms, it was not easy to create asynchronous controller actions in ASP.NET MVC till MVC 3. We had to derive the controller class from AsyncController and create async and completed methods for the controller action that performs asynchronous task. This is quite a bit of work to perform.

As ASP.NET MVC 4 runs on top of .NET framework 4.5, we can use the magical async and await keywords to simplify this process. Using these keywords, we can easily create asynchronous controller actions just like we created methods in earlier posts. Following is a sample implementation of a controller action method:

public class HomeController : Controller
{
    public async Task<ActionResult> Index()
    {
        DataServiceClient client = new DataServiceClient();
        var cities = await client.GetCitiesAsync();
        return View(cities);
    }
}

 In the above code, we are calling a WCF service asynchronously. As a method marked as async must return a Task, the return type is modified to Task<ActionResult>.

Happy coding!

No comments:

Post a Comment