Understanding async and await in c#
first of all why am I making this post when msdn and other sources has already explained it? it simply because they all confuses the reader than actually giving them information. ( or at least it was the case for me). if you are an advance c# developer you might find this post a bit trivial. but if you are fresher like me you might find this post insightful.
what's async and await and why do we use it?
so basically async and await used when we want to do some IO operations or making a web request where we don't exactly know when or if the function going to return a valid value.
we use `async` and `await` keyword to work with async code. annotate the method with `async` keywork and "wrap" the return type in `Task` . ( I am going to explain what Task is in a bit) . now after doing this if you call he async function it will be executed in the background and won't be blocking the main thread. that way you can call multiple async function in the background. but what if you want to have the return value and use it in some function? then `await` comes into the picture. ( now to explain await I need to first explain what `Task` type is and what it does)
what Task type does?
if we talk in layman term than `Task` just wraps the return value. yup that's it. what `await` actually does is that it unwraps ( yes I know you Rust people going to like this analogy ) the Task and get the return value from the Task. Think of `Task` as a bucked where all the async code put their return value. and then main thread calls `await` to actually get the value from a Task.
I hope it clears out some confusion about async/await and you learned something new!
Thank you for reading!