The C# language features async and await are very easy to use, straight forward and available right out of the box in the .NET framework. But it seems the idea behind async & await has some confusions in implementations, especially where you await in the code.
The asynchronous feature boasts about the responsiveness, but it can help boosting the performance of your application as well. Most developers seem to miss this point.
Since most projects start with the Web API, let me start the discussion from there. In a Web API action like below, the async in the action method helps the IIS threads not to be blocked till the end of the call and return immediately, thus increasing the throughput of the IIS.
When ever we have an async method developers use the await immediately right there. This makes sense when the rest of the code depends on the result of the call, otherwise this is not a wise option.
Assume we have an async operation like below.
Say that you want to invoke the method twice.
In the above code snippet, the method is asynchronous – the action method is marked as async, and IIS thread pool returns before the completion and continue from the point where it left when the response arrives.
But the method is not gaining much in the performance, this method would take 12+ seconds to complete. As it goes to the first DoWork() which takes 6 seconds and then the second DoWork() which takes another 6 seconds and finally returns.
Since the result of the first execution is not used or not needed in the rest of the execution we don’t need to perform individual awaits. We can execute this in parallel.
The above code executes the tasks in parallel and awaits at the end of the method. This model would take 6+ seconds.
Async and await are very powerful features of the .NET and they help not only being responsive but also in performance and parallel execution. By using the await carefully you gain more performance advantages.