Monday, 26 December 2011

Asynchronous MVC controllers end to end example

=== PREAMBLE ===

My intended audience:

1) You are a programmer or articial being understanding code (probably the former)
2) You work with ASP.NET MVC
3) You must take in use asynchronous processing to handle a slow and time consuming
MVC action and want to learn how to implement an AsyncController.


If this is the case, please read on!

== PREAMBLE ===


I guess many of you know how to create an ordinary MVC controller inheriting from System.Web.Mvc.Controller class, but what about creating an Asynchronous MVC controller?

It is possible to opt-in asynchronous controllers in MVC out of the box of the MVC framework. This will be a code sample of how this is possible. The goal of the asynchronous controller will be to provide better scalability, especially for complex calculations that take long which are accessed by many simultaneous users. Beware though, the standard synchronous design is easier to relate to and will be suitable in many standard scenarios. Asynchronous controllers should only be applied where there is a good reason to expect bottlenecks to be present in the code and in a real production environment.

Moving on to the asynchronous controller. Instead of inheriting from the controller class, inherit from the System.Web.Mvc.AsyncController class in MVC. The following code shows how to create an asynchronous controller.

Code sample follows:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Threading;

namespace SubstitutePartInCompositionContainer.Controllers
{
public class TestAsyncController : AsyncController
{


[AsyncTimeout(60000)]
public ActionResult IndexAsync()
{
AsyncManager.OutstandingOperations.Increment();
ThreadPool.QueueUserWorkItem((s) =>
{
ServiceReference1.NewsServiceClient client =
new ServiceReference1.NewsServiceClient();

TempData["news"] = client.GetSomeNews("Steinkjer");
AsyncManager.OutstandingOperations.Decrement();
}, null);

return View();
}

public ActionResult IndexCompleted()
{
ViewBag.DateStamp = DateTime.Now;
ViewBag.News = TempData["news"] as string;
return View();
}

}
}



The class in this example is called TestAsyncController. It inherits from the AsyncController class. The class contains two action methods which is called IndexAsync and IndexCompleted. In general, for every asynchronoous MVC action, there must be two method suffixed with Async and Completed, just like every controller must be suffixed with Controller (part of the design by contract conventions in MVC).

I put the attribute [AsyncTimeout(60000)] here, it is possible to specify in milliseconds how long an async timeout should be allowed to execute before timing out. It is also possible to use the attribute [NoAsynctimeout] instead.

Further on, I use the static method ThreadPool.QueueUserWorkItem to add an asynchronous call in the current Thread Pool. I use the AsyncManager.OutstandingOperations.Increment() and corresponding Decrement() methods to keep track of the pending asynchronous calls. AsyncManager is part of System.Web.Mvc.Async namespace. This book keeping is required for correctly arriving at the Complete method that will receive the asynchronous result. For convenience, I move the result to the TempData dictionary. This will be available for me in the Complete method in my controller. Since the data I get is a string, I just copy it to the ViewBag (dynamic object) and this is then just displayed in the MVC view Index.cshtml in the folder TestAsync.

Here is the service contract for the NewsService used (WCF service):


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace TestServices
{

[ServiceContract]
public interface INewsService
{

[OperationContract(AsyncPattern=true)]
IAsyncResult BeginGetSomeNews(string city, AsyncCallback callback,
object asyncState);

string EndGetSomeNews(IAsyncResult result);

}

}



As you can see, the WCF service tags the operation BeginGetSomeNews with the AsyncPattern equals set to true to allow asynchronous execution. Not only will the IIS service not receive a blocking call, the service itself is also run asynchronous in this case. The WCF service also got a pair of methods this time prefixed with Begin and End. Only the Begin method is attributed with [AsyncPattern=true], the end method is not even attributed with OperationItem attribute without any overloads. This is because the end method is just a callback for the Begin method. As in asynchronous programming, the Begin method starts by receiving its parameters, followed by AsyncCallback callback, object asyncState paramteters. The End method returns string in this case and also receives such an object.

The service implementation looks like this:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading;

namespace TestServices
{

public class NewsService : INewsService
{

public IAsyncResult BeginGetSomeNews(string city, AsyncCallback callback,
object asyncState)
{
Thread.Sleep(3000); //simulate some sleep
return new
CompletedAsyncResult("Here are some news for " + city);
}

public string EndGetSomeNews(IAsyncResult result)
{
var resultFromAsync = result as CompletedAsyncResult;
return resultFromAsync.Data;
}

}

}



I use a class called CompletedAsyncResult, this looks like this (MSDN is the source):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestServices
{

public class CompletedAsyncResult : IAsyncResult
{
T data;

public CompletedAsyncResult(T data)
{ this.data = data; }

public T Data
{ get { return data; } }

#region IAsyncResult Members
public object AsyncState
{ get { return (object)data; } }

public WaitHandle AsyncWaitHandle
{ get { throw new Exception("The method or operation is not implemented."); } }

public bool CompletedSynchronously
{ get { return true; } }

public bool IsCompleted
{ get { return true; } }
#endregion
}
}


Then, I just added a Service Reference to the WCF class library containing my service to generate a proxy or service agent to access my WCF service in my controller, as seen in the first code.

Important GOTCHAS about asynchronous MVC controllers:


  • There is no explicit call between the Async and Completed method in the MVC controller inheriting from AsyncController. This is code by design or contract.

  • We must "help" MVC keep track of the outstandingoperations for the AsyncManager in our code. When the counter turns to zero again, the async operation decrementing the value last will call its Complete method.. Use AsyncManager throughout.

  • Google blogger does not handle generic arguments well, but the CompletedAsyncResult object takes string as a generic type argument in my demo code here. It could be a complex type such as a data contract.

  • There are many more methods of achieving this, this is just one example.


Share this article on LinkedIn.

2 comments:

  1. The code in this blog post should be considered "Demo code". The class CompletedAsyncResult takes a generic parameter T. Google Blogger has troubles rendering the generic parameters since it believes this is ordinary HTML..


    Read about asynchronous WCF services here:

    http://msdn.microsoft.com/en-us/library/ms731177.aspx

    You will also find the CompletedAsyncResult class which implementes the IAsyncResult interface there.

    This sample is based on both MSDN and Wrox: Professional ASP.NET MVC chapter 14, Advanced topics (this is actually the final topic in the final chapter of this book, but the concepts explained here is imho intermediate).

    Regards, Tore

    ReplyDelete
  2. You can find more about AsyncManager on the MSDN page at:

    http://msdn.microsoft.com/en-us/library/system.web.mvc.async.asyncmanager.aspx

    To enforce calling the complete method, call AsyncManager.Finish(). It will bypass the Outstandingoperations count.

    ReplyDelete