I am using async and await keywords from quiet along time and feel that should be explained in light of my experience with them. There are many use cases of them but generally need them when we don't want our program to get halt while making some API call ( http / web request ). Some other use cases are :
This is first part of C# Anatomy of Async and Await series, feel free to go through all parts listed following :
- CPU bound task that took time ( using Task.Run )
- Accessing file resources ( async streams )
Above was little context that will help us understand the internal working of an async task, lets jump right into points that will help us to understand the anatomy and describe some brief explanation so that we can understand it clearly, so the first point is :
# First, we use async with a method which has await keyword inside its body, can't use one without another, its 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 start executing that statement as normal fashion and if there are some more statements in the program that needs to be executed, then main control pass 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 seprate 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 understand the anatomy of Async and Await keywords, and will give you at least a picture that how they works, there are a lots of parts in queue, meanwhile if you have any point feel free to add comment, and stay tuned.