Daniel Lang
Daniel Lang

Reputation: 6839

What advantage does an async controller give to me?

What is the difference between these two action methods?

public ActionResult Index()
{
    var task = new ServiceClient().GetProductsAsync();

    return View(task.Result);
}

public async Task<ActionResult> Index()
{
    var task = new ServiceClient().GetProductsAsync();

    return View(await task);
}

Upvotes: 3

Views: 1043

Answers (2)

jamie
jamie

Reputation: 3033

The first one will block an ASP.NET request thread until the task completes.
The second will release the thread immediately, and then grab another one when the task is complete.

What is the advantage?

A Thread is actually a pretty costly resource. It consumes OS resources, and a Thread has a Stack that contains all the variables of all the methods that were called before it got to your methods. Lets say your server is beefy enough that it can handle 100 threads. You can handle 100 requests. Lets say it takes 100ms to handle each request. That gives you 1000 requests per second.

Say it turns out that your GetProductAsync() call takes 90ms of those 100ms. Its not uncommon for a database or service to take up most of the time. Making these calls Async means that you now only need each of your threads for 10ms. Suddenly, you can support 10000 requests per second on the same server.

So the "advantage of an async controller" could be 10x more requests per second.

Of course, it all depends how scalable your backend is too, but why introduce bottlenecks when .NET does all the hard work for you. There's a lot more to it than just async, and as always the devil is in the details. There's lots of resources to help, e.g. http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

Upvotes: 2

SLaks
SLaks

Reputation: 887225

The first one will block an ASP.Net request thread until you get a result from the database.

The second one will release the ASP.Net thread immediately, then grab another one when the result comes in.

Therefore, the second one is more scalable.

Note that this answer assumes that the chain of asynchrony you're calling is correctly written and ends in actual async socket operations.

Upvotes: 6

Related Questions