Aug 11, 2014

Asynchronous vs Synchronous Method

ASP.Net processes a request (http) by using a thread from thread pool. The processing thread cannot service any other request if its being processed synchronously. This can eventually result in condition known as thread starvation. After this condition server starts queuing up the request and if the queue becomes full server starts rejecting request with 503 status code - Server Too Busy.

In IIS you can set Threads Per Processor Limit and the Queue Length (IIS->Web Server(Feature View)->ASP)

Example of how you can write async action in MVC/Web api

 public async Task Create(Product product)
 {
                .   
                .
                .
var response = await client.PostAsJsonAsync(uri, product);
                .
                .  
}
In the above example, code will be executed synchronously until it hits await key word. The await keyword registers rest of the method as a callback on the task and then it immediately return. This will free up the processing thread. When the awaited task completes, it will invoke that callback to resume the execution of the method.

This is mostly helpful for I/O bound operations. For I/O intensive activity thread tells kernel what I/O it wants done, after which it continues on, rather than sitting and waiting for response from kernel. When kernel is done with I/O it callback so that rest of the processing can be done.

On the hand if the operation is primarily CPU intensive using asynchronous action will not provide any benefits rather it will make things worse because of its overhead.



http://msdn.microsoft.com/en-us/library/hh873177(v=vs.110).aspx

No comments:

Post a Comment