Asynchronous operations in ASP.NET MVC have always been left a bit behind. They appeared in ASP.NET MVC 2, remained untouched in v3, but now in MVC 4 (especially in combination with C# 5 and async/await) they reached the same easiness of use of the standard synchronous controller. Now (or better, in a few months with the release of ASP.NET MVC 4, .NET 4.5 and C# 5) you can write

public async Task<ViewResult> Stuff() { return View(await DoStuff( "Some stuff" )); }

In this post I’m going to show how the code for implementing asynchronous controllers evolved from ASP.NET MVC 2/3 to ASP.NET MVC 4 with C# 5.

Disclaimer: The samples for ASP.NET MVC 4 are based on the Developer Preview that has been released at Build in September 2011. It might be different from the final version when it gets released.

Async Controller in ASP.NET MVC 3

In ASP.NET MVC 3 you had to create two methods, one to start the async operation, and another to end it, and you had to manually update the counters of the outstanding operations. I showed an example in blog post I wrote last month about the AsyncTimeout, but I’m copying here the code for your convenience. The code also includes the normal method I call asynchronously.

public class DoController : AsyncController { public void StuffAsync() { syncManager.OutstandingOperations.Increment(); var bg = new BackgroundWorker(); bg.DoWork += (o, e) => DoStuff( "Some other stuff" , e); bg.RunWorkerCompleted += (o, e) => { AsyncManager.Parameters[ "text" ] = e.Result; AsyncManager.OutstandingOperations.Decrement(); }; bg.RunWorkerAsync(); } public ActionResult StuffCompleted( string text) { return View( new DoStuffViewModel(){Text=text}); } private void DoStuff( string input, DoWorkEventArgs e) { Thread.Sleep(5000); e.Result = input; } }

Introducing the Task Library

The sample above uses the BackgroundWorker to call asynchronously the DoStuff method. When using ASP.NET MVC 3 with .NET 4 we could also use a Task with continuation and make it look a bit better. If you have never used the Task library I recommend you read the awesome post by Justin Etheredge: .NET 4.0 and System.Threading.Tasks.

public class DoController : AsyncController { public void StuffAsync() { AsyncManager.OutstandingOperations.Increment(); var task = Task.Factory.StartNew(() => DoStuff( "Some other stuff" )); task.ContinueWith(t => { AsyncManager.Parameters[ "model" ] = t.Result; AsyncManager.OutstandingOperations.Decrement(); }); } public ActionResult StuffCompleted( string text) { return View( new DoStuffViewModel(){Text=text}); } private string DoStuff( string input) { Thread.Sleep(5000); return input; } }

Not a lot better, but still less lines and event handling around (which I personally don’t like that much). This is as far as you can go with officially released versions of ASP.NET MVC.

Async controllers in ASP.NET 4 Developer preview

Dropped the support for .NET 3, ASP.NET MVC 4 fully embraces the Task library: no more 2 methods per action, no more manual counter increment/decrement. Your action only need to return a Task<ActionResult> and the action invoker will take care of all the synchronization.

public class DoController : AsyncController { public Task<ViewResult> Stuff() { return Task.Factory.StartNew(() => DoStuff( "Some other stuff" )) .ContinueWith(t => { return View( new DoStuffViewModel() { Text = t.Result }); }); } private string DoStuff( string input) { Thread.Sleep(5000); return input; } }

Isn’t it a lot better? It could have been even terser by using an expression:

public Task<ViewResult> Stuff() { return Task.Factory.StartNew(() => DoStuff( "Some other stuff" )) .ContinueWith(t => View( new DoStuffViewModel{ Text = t.Result })); }

So, no manual counters, no double methods. But we can go even further.

Adding async/await

If we go one one step further, to ASP.NET 4.5, with C# 5, or install the Async CTP on top of .NET 4 we get the async/await keywords. They are new features of C#, that make asynchronous code much more easy to write.

Using them, the code of our simple controller becomes:

public class DoController : AsyncController { public async Task<ViewResult> Stuff() { return View( new DoStuffViewModel() { Text = await DoStuff( "Some other stuff" ) }); } private async Task< string > DoStuff( string input) { Thread.Sleep(5000); return input; } }

Are we arrived?

Now Asynchronous controllers are as easy to do as standard controllers, and thanks to the Task library and to the async/await keywords async calls are easier to implement and less error prone than before. This raises another problem: do not overuse them. If doing async with short tasks and with lots of requests the server will spend more time in thread switching than executing your code. So never do it just for the sake of it, but use some grain of salt and do performance testing.