Async and Await


Asynchronous programming Basics and Understanding

--Thanks http://naweenblogs.blogspot.in/2014/04/async-and-await-actions-in-aspnet-mvc-4.html for the wonderful explanation.

ASP.NET has a pool of threads to service requests, when a new request comes a new thread is picked from the thread pool to service the request. Now this thread that is selected to serve the request cannot serve any other request until the initial request completes. And if this request has a high latency, such as a network operation, then the thread is also blocked until the request finishes execution. So assuming that there are a lot of concurrent high latency calls majority of the threads will be just blocked waiting for the request to finish. So as majority of the threads are just waiting and not doing any processing most of the time, the threads can be better utilized by using asynchronous programming.
In the .NET 4.5 the default maximum size of the thread pool is 5, 000 threads. Though we can extend the size of this thread pool but still the fact is that there is still some limit of the max ThreadPool size and it is always nice not to exhaust this limit of the ThreadPool.
It’s simple to implement asynchronous action methods using the await and async keywords in.NET 4.5.Let’s see how we can implement an action method that makes a network call first using the normal sequential approach and then using the new asynchronous programming approach using the async and await keywords.



using System;
using System.Threading.Task;

class Program
{
        public static void Main()
        {
        Console.WriteLine(" I am from the main thread");
        var objects= new AsyncDemo();
        objects.longRunningProcess();
        Console.Writeline(" I have finished Execution ");

        }
}

public class AsyncDemo
{
        public async Task longRunningProcess()
        {
        Console.WriteLine("I am from the AsyncDemo Thread");
        int a=await GetMeValue();
        Console.WriteLine("Hey I have got a value !!! 'Its "+a);
        Console.WriteLine("Now I can Exit");
        }

        public int GetMeValue()
        {
        Thread.Sleep(9000);
        return 5;
        }
}

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6