Sunday, July 5, 2020

C# Anatomy of Async and Await - Part 1

This is first the part of C# Anatomy of Async and Await series, feel free to go through all parts listed below :

I have been using async and await keywords for a long time and I feel that these should be explained in light of my experience. There are many cases for using them but generally, we need them when we don't want our program to get halt while making some API call ( http / web request ). Some other cases for using them are :

  • CPU bound task that took time ( using Task.Run )
  • Accessing file resources ( async streams )

Above was a little context that will help us to understand the internal working of an async task. Let’s jump right into points that will assist us to understand the anatomy and describe some brief explanations so that we can understand it clearly. Thus the first point is : 


# First, we use async with a method which has await keyword inside its body. We can't use one without the other, it’s the rule.

Explanation : There will be compile time error if we miss any keyword.


#Second, we only use await keyword with method call ( await SomeMethod(); ) which returns Task or Task<T>

Explanation : When we call a method which returns Task or Task<T>, the current thread starts executing that statement as normal fashion and if there are some more statements in the program that are needed to be executed, then the main control passes the execution of that method to another thread ( from thread pool ) and jumps back to the next statement and the only way to get results out from that method is to put await keyword in front of it.


And this is enough for this part, now we can see the real benifit of async and await keywords in context of tasks and if we conclude our findings we can say, multiple methods that are returning task ( or consuming tasks ) can be run sequentially if we put await in front of their calls.
Or can run concurrently on a separate Thread if we just call them and await them at the end of the calling function which will save our time for executing those functions.

I hope above article will help you to understand the anatomy of Async and Await keywords, and will give you at least a picture that how they work, there are a lot of parts in queue, meanwhile if you have any point, feel free to add comment, and stay tuned.

No comments:

Post a Comment

Lets play with cypress - Part 2

 In the first part I explained starting of my automation journey with first command to setup cypres at the end i.e.  npm install cypress -g...