Asp.Net MVC Exploring Controllers in-depth Part 9

Asp.Net MVC Exploring Controllers in-depth Part 9

Asynchronous Controllers

 

  • The async actions are useful only when you are performing I/O bound operations such as remote server The benefit of the async call is that during the I/O operation, no ASP.NET worker thread is being used.
  • The asynchronous controller enables you to write asynchronous action
  • Suppose we have three operations which take 200, 500 and 800 milliseconds. With the synchronous call, total response time would be slightly more than 1500 milliseconds. However, if the calls are made asynchronously (in parallel), total response time would be slightly more than 800 milliseconds, because that is the duration of longest task/operation.

Note:

It allows you to perform long running operation(s) without making the running thread idle. It does not mean it will take lesser time to complete the action. If a request makes a service call that requires two seconds to complete it, the request will take two seconds whether it is performed synchronously or asynchronously. However, during the asynchronous call, the server is not blocked from responding to the other requests.

Asynchronous Controllers Prior to MVC 4 / C# 4

Here is what we need to do:

  • The controller has to derive from AsyncController instead of Controller
  • The action needs to be split into two parts: the first part begins all asynchronous calls and the second part uses the results of those calls to return the action result

Asynchronous Controllers in MVC 4 or 5 / C# 5:

From C# 5 we have Task parallel API and same can be used for implementing Asynchronous call to action methods.

Example:

Problem:

While our new asynchronous controller achieves parallelism between requests, it calls methods in sequence. If each call takes 1 second, this method will return the action result in little more than 3 seconds.

Let’s see how we can parallelize the requests.

Here we first invoke all 3 asynchronous Operations calls and only then await them using Task.WhenAll. Finally, we use the await on each task to get the return value of all 3 operations.

learn MVC at your own pace – MVC tutorial

Please follow and like us:
0

Leave a Reply

Your email address will not be published. Required fields are marked *