April 5, 2012 09:59 by
Scott
Microsoft is ramping up the release cycles of some of its products, and the phenomenal rate at which the ASP.NET MVC framework is being updated is testament to that.
The latest version, MVC 4 Developer Preview, has some cool new additions to its armory. Over the next few weeks, I’ll be taking a look at some of the features new to the framework, and how you might use these in your website.
The more noticeable features added to the framework include:
- Mobile project templates
- Display modes
- Recipes
- Task support for Asynchronous controllers
- Azure SDK
- Bug fixes
Installation
Before undertaking any development, you’ll need to install the MVC 4 builds. The simplest way to do this is via the Web Platform Installer. MVC 4 is available for Visual Studio 2010 or Visual Studio 2011 Developer Preview. All of the MVC articles I’m authoring are developed in Visual Studio 2011 Developer Preview. Below are the links to get started.
- ASP.NET MVC 4 for Visual Studio 2010
- ASP.NET MVC 4 for Visual Studio 2011 Developer Preview
Task Support for Asynchronous Controllers
The feature I’m going to be focusing on today is task support for asynchronous controllers.
Nobody likes to wait, so why should your users wait for a long-running asynchronous task? It doesn’t make sense!
Developing asynchronous controllers has been available since MVC 3, but for this to work you had to write a bunch of extra code – what I like to refer to as code noise – to get it to work.
Take the example of integrating Twitter into a webpage. In MVC 3, the code needed to follow specific rules. Instead of there being one action method, there had to be two action methods. Both were named the same, but for the method beginning the asynchronous request, you needed to append Async to the action name. For the method handling the ending of the asynchronous request, you needed to append Completed to the action name.
It’s much easier to follow if you see some code. The sample code below requests data from Twitter asynchronously.
public void SearchTwitterAsync()
{
const string url = "http://search.twitter.com/search.atom?q=guycode&rpp=100&result_type=mixed";
// the asynchronous operation is declared
AsyncManager.OutstandingOperations.Increment();
var webClient = new WebClient();
webClient.DownloadStringCompleted += (sender, e) =>
{
AsyncManager.Parameters["results"] = e.Result;
AsyncManager.OutstandingOperations.Decrement();
};
webClient.DownloadStringAsync(new Uri(url)); //the asynchronous process is launched
}
public ActionResult SearchTwitterCompleted(string results)
{
// Now return the twitter results to the client
return Json(ReadTwitterResults(results), JsonRequestBehavior.AllowGet);
}
The code above is going off to Twitter, searching for data and returning the results asynchronously. There’s a lot of code noise in there and to me, it’s violating – for want of a better word – the Don’t Repeat Yourself (DRY) principle.
Well, in MVC 4, these tasks have been rolled into one. You can now write asynchronous action methods as single methods that return an object of type Task or Task<ActionResult>.
These features are only available in MVC 4 or C# 5. Here’s the simplified code below.
public async Task<ActionResult> Search()
{
string url = "http://search.twitter.com/search.atom?q=guycode&rpp=100&result_type=mixed";
var webClient = new WebClient();
string xmlResult = await webClient.DownloadStringTaskAsync(url);
return Json(ReadTwitterResults(xmlResult), JsonRequestBehavior.AllowGet);
}
The results are the same, but now you can reduce the amount of code you need to accomplish the same outcome.
Asynchronous action methods that return Task instances can also support timeouts. To set a time limit for your action method, you can use the AsyncTimeout attribute. The following example shows an asynchronous action method that has a timeout of 2500 milliseconds. Once it has timed out, the view “TimedOut” will be displayed to the user.
[AsyncTimeout(2500)]
[HandleError(ExceptionType = typeof(TaskCanceledException), View = "TimedOut")]
public async Task<ActionResult> Search()
{
string url = "http://search.twitter.com/search.atom?q=guycode&rpp=100&result_type=mixed";
var webClient = new WebClient();
string xmlResult = await webClient.DownloadStringTaskAsync(url);
return Json(ReadTwitterResults(xmlResult), JsonRequestBehavior.AllowGet);
}
Nothing else has changed with asynchronous actions.
The controller still needs to derive from AsyncController, and you still access the action in the same way but you have to write less code.
Asynchronous controllers are perfect for pieces of code that run to great length. Most of the time you’ll be working with a database, so being able to make calls to the database asynchronously is a big plus for the end user.
Why should they wait?
Test drive for NEW ASP.NET MVC 4 for FREE, please visit our site at http://www.hostforlife.eu/ASPNET-45-Beta-European-Hosting.aspx.