Friday, June 3, 2011

AsyncController in Asp.Net MVC








Guys,
Here goes the first entry of 'About my experience with Asp.Net mvc and Windows Azure series'.
I had an requirement, where in for most of the actions, i was suppose to fetch the data from the database through WCF Services but not at the cost of blocking/reducing the throughput of Asp.net mvc application....


Then i was thinking like in order to have Non blocking/high throughput - i need to make use of some asynchronous api from .Net to do the task such as either ThreadPool's QueueUserwork items , or Delegates or some asynchronous reader kind of api's....But then i surfed internet and found that there is a specific way by which this can be achieved in Asp.Net mvc......
Here are the steps by which we can get it working....


1. First create the set of WCF Services which will get the data from the database.
2. By right clicking the Asp.Net MVC project, add the service reference pointing to the wcf project.
3. During the step 2 - click on the advanced button and check 'generate asynchronous operations'
4. Inside the Asp.Net mvc project, ensure that controller class is derived from AsyncController than the default Controller class
5. For the method, Ensure that ActionName ends with 'ActionAsync' - for instance 'indexAsync'.
6. Ensure that the return type of 'ActionAsync' is void than the default ActionResult, because this method executes asynchronously.
7. Create one more method corresponding to the ActionAsync with the name - 'ActionCompleted' for instance 'indexCompleted' where in the result is returned once the action executes successfully.
8. Inside indexAsync - make a call to the wcf proxy on the asynchronous methods...for instance proxy.GetDataAsync();
9. For the callback of wcf proxy ie proxy.GetDataCompleted() - hook up the event handling by using the special class from asp.net mvc - 'AsyncManager' as shown in the following image.
10. AsyncManager's parameter class help to pass the value to the method
11. As you could see in the image, we also need to increment and decrement the async operation count - which we should be doing by using AsyncManager class.


Thats it, we achieved what we intended to.....


I hope this helps!...


If you have any queries , please do let me know..


Regards,
-Vinayak







No comments: