Open In App

Async and Await in C#

Improve
Improve
Like Article
Like
Save
Share
Report

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.

Synchronous Programming:

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.

Example 1:

C#




// C# program 
using System;
using System.Threading;
public class GFG{
  
    static void Main(string[] args)
        {
  
            Demo();
            Console.ReadLine();
  
        }
        public static void Demo() {
            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            StartSchoolAssembly();
            TeachClass12();
            TeachClass11();
            watch.Stop();
            Console.WriteLine($"Execution Time: 
                              {watch.ElapsedMilliseconds} ms");
              
        }
          
          
        public static void StartSchoolAssembly()
        {
            Thread.Sleep(8000);
            Console.WriteLine("School Started");
        }
  
  
        public static void TeachClass12()
        {
            Thread.Sleep(3000);
            Console.WriteLine("Taught class 12");
  
        }
  
        public static void TeachClass11()
        {
            Thread.Sleep(2000);
            Console.WriteLine("Taught class 11");
  
        }
    
}


Output:

 

Asynchronous Programming:

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.

Example 2:

C#




// C# program for async and await
using System;
using System.Threading;
using System.Threading.Tasks;
  
public class GFG{
  
    static void Main(string[] args)
        {
  
            Demo();
            Console.ReadLine();
  
        }
  
        public static void Demo() {
            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();
  
            var task1 = StartSchoolAssembly();
            var task2 = TeachClass12();
            var task3 = TeachClass11();
  
  
            Task.WaitAll(task1, task2, task3);
            watch.Stop();
            Console.WriteLine($"Execution Time:
                              {watch.ElapsedMilliseconds} ms");
              
        }
          
          
        public static async Task StartSchoolAssembly()
        {
            await Task.Run(() =>
            {
                Thread.Sleep(8000);
                Console.WriteLine("School Started");
            });
        }
  
  
        public static async Task TeachClass12()
        {
            await Task.Run(() =>
            {
                Thread.Sleep(3000);
                Console.WriteLine("Taught class 12");
            });
              
  
        }
  
        public static async Task TeachClass11()
        {
            await Task.Run(() =>
            {
                Thread.Sleep(2000);
                Console.WriteLine("Taught class 11");
            });
              
  
        }
    
}


Output:

 

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.

Example 3:

C#




// C# program for await keyword
using System;
using System.Threading;
using System.Threading.Tasks;
  
public class GFG
{
  
    static void Main(string[] args)
    {
  
        Demo();
        Console.ReadLine();
  
    }
  
    public static async void Demo()
    {
        var watch = new System.Diagnostics.Stopwatch();
        watch.Start();
  
        var task1 = StartSchoolAssembly();
        await task1;
        var task2 = TeachClass12();
        var task3 = TeachClass11();
  
  
        Task.WaitAll(task1, task2, task3);
        watch.Stop();
        Console.WriteLine($"Execution Time: 
                          {watch.ElapsedMilliseconds} ms");
  
    }
  
  
    public static async Task StartSchoolAssembly()
    {
        await Task.Run(() =>
        {
            Thread.Sleep(8000);
            Console.WriteLine("School Started");
        });
    }
  
  
    public static async Task TeachClass12()
    {
        await Task.Run(() =>
        {
            Thread.Sleep(3000);
            Console.WriteLine("Taught class 12");
        });
  
  
    }
  
    public static async Task TeachClass11()
    {
        await Task.Run(() =>
        {
            Thread.Sleep(2000);
            Console.WriteLine("Taught class 11");
        });
  
  
    }
  
}


Output:

 

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.



Last Updated : 04 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads