Sunday, 2 July 2017

Async in C#


    All started when i asked the question about difference between Node.Js and C# .Net. It ended that the answer is how they handle request in asynchronous operation.

Asynchronous programming has always been a grey box for me, i understand how it works but not sure how thread process requests and how it works inside C#. I really did have lots of questions before, that has fuzzy answers.

Now i have better understanding about asynchronous programming. Hope you have these questions too, because if you have answer for the below questions, you should better understand the asynchronous programming and how node.js server and IIS works.  I write the blog in assumption you know the syntax of async pattern and have programmed a bit using async and TPL libraries, if you want more about the syntax of the async pattern, you can find it here

  • What is Asynchronous programming ?
  • Difference between Node Js vs C# asynchronous programming model ?
  • Asynchronous program runs on multiple threads ?
  • Why there is Task Keyword ?
  • When should i use await ?
  • When should i use Task.Run()

What is Asynchronous programming ?


    Before jumping into async pattern, let us look into asynchronous programming, asynchronous programming is nothing but, not blocking the thread, it started on.

Whenever there is request, a thread start processing the request, then IF it finds the request needs a  I/O or database or network operation, the current thread does not wait for the thread to complete, it just says “tell me when you’re done”. 

 

Difference Node Js vs C# asynchronous programming model ?


The main difference between Node Js and C# is their programming model. (Basically comparing Node Js and IIS server)

In case of Node Js, it offers only asynchronous programming model, meaning node js is built on assumptions that all your web application will use I/O or database or network resources etc to satisfy  their request. So the asynchronous (callback) is by default.

Whereas in C# we have an option of either using asynchronous programming model or synchronous (blocking thread).

So whenever there is a request to Node.Js server, the thread takes the request and then delegates to the other resource threads through event queue. Main thread is released to process other request that comes in, so the main thread is never blocked.

But in case of C#, Synchronous programming model, thread will process the request, whenever there is a database call or I/O call then  the thread waits itself for the external requested to be processed. So when the other request that comes to our IIS server has to wait. 

Await and async makes it asynchronous and makes it work like node js.Whereas in Node js, by default follows asynchronous model.

    

Asynchronous program runs on multiple threads ?

 

     Asynchronous does not mean it run on multiple thread, it only means the thread is not blocked or does not waits on any operation to complete. If we have multiple core system then the process is carried out by the number of threads available. Do not confuse multi threading with asynchronous programming model, async programming model can work in single thread environment too.



Why there is Task Keyword ?


    Task keyword is used in .Net technologies to denote the asynchronous programming model, it goes with async keyword denoting that the method is of asynchronous type and it returns the Task in future.

When should i use await ?


    Await keyword goes in synonymous with async keyword. We will look into how the compiler works when it reaches await keyword.  Below is the example we will use for  explanation.

In this example we are trying to download images from different website.

 private async Task AddFavicon(string domain)
       {
           WebClient webClient = new WebClient();
           byte[] bytes = await webClient.DownloadDataTaskAsync("http://" + domain + "/favicon.ico");
           Image imageControl = MakeImageControl(bytes);
           m_WrapPanel.Children.Add(imageControl);
       }

In the above example, until the compiler finds the await keyword, the execution is synchronous, the magic of asynchronous happens only when the await keyword is processed.

byte[] bytes = await webClient.DownloadDataTaskAsync("http://" + domain + "/favicon.ico");

When the compiler finds the await keyword, the current thread is released. The code below the await keyword is moved to separate part of execution, and the separate part is executed once the download is completed by the same thread or different thread. 

 When should i use Task.Run() ?


    Task.Run is used to start a separate new thread. It is mostly used to free up the UI thread to avoid freezing the UI.

I will share my experience why i needed a Task.run in the first place, i have old web api application which does not have async programming model implemented, but i need to incorporate the Active directory B2C into our application which only supports async methods. Now when i use await on the B2C get method which is async, the process suspends and does not return to the main thread of the Web api application, this happened intermittently, so i want run this async method and return to my main thread. So i have to start a new thread and make it run using Task.Run and i had control of the return and it solved the problem. Short answer is “You need a separate new thread, you can use Task.Run()”.

Leave a comment to share what you learned, and hit the “like” button to let others know about it (make sure you’re logged into Facebook to like and comment).



No comments:

Post a Comment

Note: only a member of this blog may post a comment.

Build Bot using LUIS