Old-way of asynchronous programming in ASP.NET MVC 3 On ASP.NET MVC, I try to write an async Controller action with the old asynchronous programming model (actually, it is the current one, new one is still a CTP). 

Here, I am trying to run 4 operations in parallel and it worked great. Here is the complete code:

public class SampleController : AsyncController {

    public void IndexAsync() {

        AsyncManager.OutstandingOperations.Increment(4);

        var task1 = Task&lt;string&gt;.Factory.StartNew(() =&gt; {

            return GetReponse1();
        });
        var task2 = Task&lt;string&gt;.Factory.StartNew(() =&gt; {

            return GetResponse2();
        });
        var task3 = Task&lt;string&gt;.Factory.StartNew(() =&gt; {

            return GetResponse3();
        });
        var task4 = Task&lt;string&gt;.Factory.StartNew(() =&gt; {

            return GetResponse4();
        });

        task1.ContinueWith(t =&gt; {

            AsyncManager.Parameters["headers1"] = t.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });

        task2.ContinueWith(t =&gt; {

            AsyncManager.Parameters["headers2"] = t.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });

        task3.ContinueWith(t =&gt; {

            AsyncManager.Parameters["headers3"] = t.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });

        task4.ContinueWith(t =&gt; {

            AsyncManager.Parameters["headers4"] = t.Result;
            AsyncManager.OutstandingOperations.Decrement();
        });

        task3.ContinueWith(t =&gt; {

            AsyncManager.OutstandingOperations.Decrement();

        }, TaskContinuationOptions.OnlyOnFaulted);
    }

    public ActionResult IndexCompleted(string headers1, string headers2, string headers3, string headers4) {

        ViewBag.Headers = string.Join("&lt;br/&gt;&lt;br/&gt;", headers1, headers2, headers3, headers4);

        return View();
    }

    public ActionResult Index2() {

        ViewBag.Headers = string.Join("&lt;br/&gt;&lt;br/&gt;", GetReponse1(), GetResponse2(), GetResponse3(), GetResponse4());

        return View();
    }

    #region helpers

    string GetReponse1() {

        var req = (HttpWebRequest)WebRequest.Create("http://www.twitter.com");
        req.Method = "HEAD";

        var resp = (HttpWebResponse)req.GetResponse();

        return FormatHeaders(resp.Headers);
    }

    string GetResponse2() {

        var req2 = (HttpWebRequest)WebRequest.Create("http://stackoverflow.com");
        req2.Method = "HEAD";

        var resp2 = (HttpWebResponse)req2.GetResponse();

        return FormatHeaders(resp2.Headers);
    }

    string GetResponse3() {

        var req = (HttpWebRequest)WebRequest.Create("http://google.com");
        req.Method = "HEAD";

        var resp = (HttpWebResponse)req.GetResponse();

        return FormatHeaders(resp.Headers);
    }

    string GetResponse4() {

        var req = (HttpWebRequest)WebRequest.Create("http://github.com");
        req.Method = "HEAD";

        var resp = (HttpWebResponse)req.GetResponse();

        return FormatHeaders(resp.Headers);
    }

    private static string FormatHeaders(WebHeaderCollection headers) {

        var headerStrings = from header in headers.Keys.Cast&lt;string&gt;()
                            select string.Format("{0}: {1}", header, headers[header]);

        return string.Join("&lt;br /&gt;", headerStrings.ToArray());
    }

    #endregion

}


I have also Index2 method here which is synchronous and does the same thing.

I compare two operation execution times and there is major difference (approx. 2 seconds)

But I think I am missing lots of things here (exception handling, timeouts, etc). I only implement the exception handling on task3 but I don't think it is the right way of doing that. 

What is your opinion on this code? How can it be improved?
There is a lot of code repetition. I would create a custom class that inherits from Task and make it generic enough so you can have an array of your custom class and just loop through that array to do what you need to do.

class TaskController&lt;T&gt; : Task&lt;T&gt;
{
    public TaskController(AsyncManager asyncManager, string asyncManagerParameter, Func&lt;T&gt; callback) : base(callback)
    {
        this.ContinueWith(t =&gt;
        {
            //just for demonstration
            Console.WriteLine(t.Result);

            // Do some work with your asyncManager
            asyncManager.Parameters[asyncManagerParameter] = t.Result.ToString();
        });
    }
}


I would also have GetResponse take a string uri as parameter instead of making a new GetResponse for each url that you want to use. 

public static string GetResponse(string uri)
{
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
    req.Method = "HEAD";

    HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

    return resp.Headers.ToString(); // just changed this for demonstration purposes
}


and finally I would use it like this

AsyncManager asyncManager = new AsyncManager();

TaskController&lt;string&gt;[] taskControllers = {
    new TaskController&lt;string&gt;(asyncManager, "header1", () =&gt; GetResponse("http://google.com")),
    new TaskController&lt;string&gt;(asyncManager, "header3", () =&gt; GetResponse("http://www.twitter.com"))
};

foreach (TaskController&lt;string&gt; tc in taskControllers)
{
    tc.Start();
}


It is much less code, you can reuse it later, you can very easily add a new TaskController if you want to work with another URL, and it's a lot more readable.

To use this you will need to just edit this.ContinueWith inside TaskController and have it do whatever you want (decrement, etc)