Async and Await in C#
Async and Await are the two keywords that help us to program asynchronously. An async keyword is a method that performs asynchronous tasks such as fetching data from a database, reading a file, etc, they can be marked as “async”. Whereas await keyword making “await” to a statement means suspending the execution of the async method it is residing in until the asynchronous task completes. After suspension, the control goes back to the caller method. Once the task completes, the control comes back to the states where await is mentioned and executes the remaining statements in the enclosing method.
Let us see the behavior of the code with and without async and await operators.
In general, the code executes sequentially i.e statements are executed one after the other. Let us take a small example of a school that has classes 11 and 12.
- The first thing school does is start the assembly which might be having morning prayer, pledge, daily updates, etc
- After the assembly, teachings begin for class 11 & class 12.
In our synchronous code below, we will be using the Stopwatch to record the execution time taken by the code. We have three methods in which Thread.Sleep(n) is specified to simulate that these methods take some time to run.
Using asynchronous programming indicates that a method can execute without waiting for another method to complete. Using async and await, we can run the methods above parallelly.
Notice that these methods above have run parallelly and the execution time taken will be the same as the time taken by StartSchoolAssembly() as this is the method that is taking the longest time.
Do we really want this output? How can we start teaching classes 11 and 12 without starting the school assembly? Let us wait for the school assembly to finish irrespective of how long it is taking and later the teaching for classes 11 and 12 can begin.
Here task1 represents the school assembly. Therefore let us use the await keyword to wait for the school assembly task to finish.
Notice that the TeachClass12() and TeachClass11() execute only after the StartSchoolAssembly() completes. The school assembly takes 8 seconds to complete. Class 11 finishes the class soon as it takes only 2 seconds. Class 12 finishes a bit late as it takes 3 seconds. Therefore the total execution time is 8s + 3s = 11s.