• How to Write Asynchronous Controller Class in ASP.NET MVC

    by  • January 28, 2016 • Microsoft ASP.NET MVC • 0 Comments

    First of all, we should learn, what do Asynchronous events mean? The events are asynchronous when they don’t happen at same time. Our telephone conversation is ‘synchronous’ as we have to respond after the conversation stops and email is ‘asynchronous’ as we respond whenever its convenient.

    Asynchronous controllers are to improve the efficiency of thread pooling in web server. First we try to understand, how thread pooling works in web server. MVC application get hosted in IIS Server. The IIS Server maintains the pool of threads to meet the request that comes to the web server. When a request comes to the MVC application , the IIS Server takes a thread from the thread pool and serves the request. That thread can not be used for another request before the completion of the first request. For another request, there will be another thread. Lets suppose a thread pool has only 2 threads. Third request has to wait for the thread to serve. This situation is called as ‘Thread Starvation’. In this article we will learn, how can we stop thread starvation by using MVC asynchronous controllers.

    Let us first create a synchronous controller name it as ‘Simple Controller’ with action called as LongTask as shown below;

    SimpleController.cs

    In the above code, inside the LongTask action method, there is a pause of ten seconds and after ten seconds this method invokes a view called as LongTask.aspx.Now lets look at the LongTask View code given below;

    LongTask.cshtml

    In this view, we have just mentioned that controller has finished execution. Now whenever the Longtask action will called, this will pause for ten seconds and after ten seconds, it will invoke the View.

    Now in the Web.Config file,  we will limit the threads in the thread pool to 2 in the process model tag as shown below;

    In the above code, the thread limit is two. It means, third request has to wait for thread. Suppose if there are fifty users and each user call the method LongThread to execute a particular task , so there will be thread starvation.  This ‘thread starvation’ can be stopped by writing asynchronous controllers.

    Lets look at the code below;

    In the above code, we have created asynchronous controller by keyword async and await. Now the long task action method is asynchronous and in this method we call a method BigTask and write await keyword before this.  This means BigTask will wait and release the thread for other request and when the BigTask method completes a new thread will return a view LongTask. In this way other request will not have to wait for thread.

     




    Namecheap.com

    Leave a Reply