07 November 2013

async/await with MVC4

The .NET 4.5 Framework introduced the new async/await asynchronous programming model. With ASP.NET MVC 4 comes the application of the async/await model to controller actions. A traditional ASP.NET MVC control action will be synchronous by nature; this means a thread in the ASP.NET Thread Pool is blocked until the action completes. Calling an asynchronous controller action will not block a thread in the thread pool. The greatest advantage of using this is to bring UI more responsive.
Well before .NET 4.5 (and MVC 4), we need to controller to inherit from AsyncController and implement this. With latest release this made simple and brought up to language level. To do Async in ASP.NET MVC, all you have to is return a Task and use the async keyword in your action methods.
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. Following is a sample implementation of a controller action method:
Enough of theory, let’s walk the talk.

   1:  public class HomeController : Controller
   2:  {
   3:      public async Task<ActionResult> Index()
   4:      {
   5:          Task<int> weatherInfoTask = WeatherApi.GetFollowersAsync();
   6:          Task<int> stockTickerTask = StockTickerApi.GetFollowingAsync();
   7:          await Task.WhenAll(weatherInfoTask, stockTickerTask);
   8:          ViewBag.WetherInfo = await weatherInfoTask;
   9:          ViewBag.StockTicker = await stockTickerTask;
  10:          return View();
  11:      }
  12:  }

Here we first invoke both asynchronous Weather API calls and only then await them using Task.WhenAll. Finally, we use the Result property of each task to get the Weather and Stock Ticker info.
An async method will be run synchronously if it does not contain the await keyword.  In the above code, we are calling a WCF services asynchronously. As a method marked as async must return a Task, the return type is modified to Task.await pauses the method until the operation completes.
Well, to conclude:
async: A method modifier that signals to the .NET language compiler that the marked method will run within its own thread, and that execution cannot continue past the point until the awaited asynchronous process is finished. Meanwhile, control is returned to the caller of the async method.
await: An operator that suspends the execution of the method to which it applies. When called, an asynchronous method synchronously executes the body of the function up until the first await expression on an awaitable instance that is not yet completed, at which point the invocation returns to the caller.
In this tutorial we learned how writing asynchronous controllers is a powerful optimization that has become much easier to implement since MVC 4 and C# 4.5.

No comments: