Asynchronous controller enables us to create asynchronous action methods in our application.ย This allows us to perform long running operation without making the running thread idle.ย Asynchronous action methods are useful when an action must perform several independent long running operations.

Synchronous

In Synchronous, if you making request, then you will have to wait till the response, you may not do other process until it response.

Asynchronous

In Asynchronous , if you making request, then you don’t need to wait for the response and we can perform any other process/task. Whenever the response arrive, you can receive in call back delegate.

What is Thread starvation in WebServer ?

Task

  • From above, the request from Request A, Request B are accepted and processing but Request C not able to get the thread because the size of the pool is 2 so this situation is called thread starvation.
  • In this case we may get Server Busy Error

As per MSDN, When a request arrives, a thread from the pool is dispatched to process that request.ย If the request is processed synchronously, the thread that processes the request is blocked while the request is being processed, and that thread cannot service another request.

This might not be a problem, because the thread pool can be made large enough to accommodate many blocked threads. However, the number of threads in the thread pool is limited. In large applications that process multiple simultaneous long-running requests, all available threads might be blocked. This condition is known asย thread starvation

If you have multiple long-running requests, all available threads might be blocked and the Web server rejects any additional request with an HTTP 503 status

(Server Too Busy).

To overcome this, ASP.NET MVC provide asynchronously call in controller/action

Here let we see the asynController

How to convert controller to asynchronously

To convert a synchronous action method to an asynchronous action method involves the following steps:
1) Before we deriving the controller from Controller, now we want to derive it from AsyncController. Controllers that derive from AsyncController enable

ASP.NET to process asynchronous requests, and they can still service synchronous action methods.

Example

We want to apply “Async” before controller like

public class AsynchronuosController : AsyncController

The “OutstandingOperations” property tells ASP.NET about how many operations are pending.ย It is needed because ASP.NET dont known how many operations were initiated by the action method or when those operations are complete. Whenย OutstandingOperations property is zero, ASP.NET completes its process by(asynchronous operation) calling the Completed method.

Example

AsyncManager.OutstandingOperations.Increment();
AsyncManager.OutstandingOperations.Decrement();

If we calling two method inside the action then we want to increment by 2 (AsyncManager.OutstandingOperations.Increment(2))

Sample Program: