Geeks With Blogs
Rajesh Pillai My experiments with asp.net mvc, jquery, wpf, silverlight, sharepoint, tdd and design patterns.

This post touches the ASP.NET MVC async controller.  Its included in the futures library and is available on codeplex.  
This may become part of ASP.NET MVC 2.  Download and add reference to the "Microsoft.Web.Mvc" dll.  Make the
following changes in the Global.asax to set the rounte to handle async request.

      public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapAsyncRoute("Default.aspx", "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = "" }
            );
        }

 

In the above route the "Index" action on the "Home" controller is mapped to async route.  Note the "MapAsyncRoute" for
sync calls you use MapRoute(..).

Let's quickly have a look at the controller.

namespace AsynPortal.Controllers
{
    public class HomeController : AsyncController
    {
        // The async framework will call this first when it matches the route
        public void Index()
        {
            // Set a default value for our result param
            // (will be passed to the MyActionCompleted method below)            

            // Indicate that we're performing an operation we want to offload

            AsyncManager.OutstandingOperations.Increment(2);

            var client = new WebClient();

            client.DownloadStringCompleted += (s, e) =>
            {
                if (!e.Cancelled && e.Error == null)
                {
                    // We were successful, set the result
                    AsyncManager.Parameters["site1"] = e.Result;
                }
                // Indicate that we've completed the offloaded operation
                AsyncManager.OutstandingOperations.Decrement();
            };

            // Actually start the download
            client.DownloadStringAsync(new Uri("http://geekswithblogs.net/rajeshpillai"));

            var client1 = new WebClient();

            client1.DownloadStringCompleted += (s, e) =>
            {
                if (!e.Cancelled && e.Error == null)
                {
                    // We were successful, set the result
                    AsyncManager.Parameters["site2"] = e.Result;
                }

                // Indicate that we've completed the offloaded operation
                AsyncManager.OutstandingOperations.Decrement();
            };

            // Actually start the download
            client1.DownloadStringAsync(new Uri("http://www.google.com"));
        }

        // This will be called when the outstanding operation(s) have completed

        public ActionResult IndexCompleted(string site1, string site2)
        {
            return View("Index", new PortalViewModel
            {
                Site1 = site1,
                Site2 = site2
            });
        }
    }
}

 

The above Index() method sets up two asynchronous request.  Evern async method has its "actioncompleted" method
also.  In the above case it is "IndexCompleted" method.

The line AsyncManager.OutstandingOperations.Increment(2) sets that two operations will be running in async mode.   The
IndexCompleted action method is invoked once all the async method is completed execution.  The parameters are passed
to the IndexCompleted method by

                    AsyncManager.Parameters["site2"] = e.Result;

To indicate that the method completed execution call the

AsyncManager.OutstandingOperations.Decrement() method.

 

The model is declared below.

namespace Demo.Model
{
    public class PortalViewModel
    {
        public string Site1 { get; set; }
        public string Site2 { get; set; }
    }
} 

You can use this model to render the "Index" view as desired.

I have used a simple demonstration of fetching website html's asynchronously. In real application problems this could be a call to a service or a database or any IO intensive operation that you need to optimize. IO intensive operations gain more benefits than CPU intensive operation.

 Hope you enjoyed this post.

 

Posted on Tuesday, December 1, 2009 11:00 PM asp.net mvc | Back to top


Comments on this post: ASP.NET MVC Asynchronous controller

# re: ASP.NET MVC Asynchronous controller
Requesting Gravatar...
Interesting article, but is there anyway we can make a Async Module like WebClient that accept multiple value like:

Download(string a)
Download(string a, string b)

What do you suggest?

if reply please send an copy to me :) duc at ducdigital dot com
Left by Ta Duc on Jan 11, 2010 5:20 AM

# re: ASP.NET MVC Asynchronous controller
Requesting Gravatar...
Great guide. Thanks for sharing your skill.
Left by jcpenney coupons on Jun 04, 2011 6:14 PM

Your comment:
 (will show your gravatar)


Copyright © Rajesh Pillai | Powered by: GeeksWithBlogs.net