Asynchronous Programming In C#


In this article, we will learn about asynchronous programming in depth using a coding example.
You will also learn how asynchronous programming reduces the waiting time for the main thread when a long running task is being performed.

What is Asynchronous programming?

Asynchronous means multiple things occurring at the same time.This is a very good approach in maximizing the use of CPU cycle at its best.
This wil not let the CPU remain idle when executing a long-running task, instead it will move it to perform some other task at the same time. 
Using this approach, if one task is blocked in executing a long block of code, then one can switch to perform other task in between.

How does Synchronous programming work? 

In the below code snippet, there are 2 synchronous methods called in the main method/main thread. And one can see that 'Y' method will be taking longer to execute due to some running logic written in it. But, still the compiler will wait for method 'Y' to finish completely before invoking method 'Z'.
Hence, here CPU cycle is not utilized properly.
Also, you will notice that  in synchronous calling, the order of invoking will always be first come first serve.
  1. private static void Y()    
  2. {    
  3.     for(int i = 0; i<999999999; i++)  
  4.       {  
  5.         // some logic  
  6.       }  
  7.     Console.WriteLine("Sync Y method called from main");    
  8. }    
  10. private static void Z()    
  11. {    
  12.     Console.WriteLine("Sync Z method called from main");    
  13. }       
  15.  static void Main(string[] args)    
  16. {         
  17.    // calling Y and  then Z sequentially    
  18.     Y();    
  19.     Z();    
  20.  }     
The output of the above code snippet is as below,
  • Sync Y method called from main
  • Sync Z method called from main 

What should be the approach to take maximum advantage  of CPU/Core for the above problem?

While method 'Y' was put on hold or taking time to execute, the compiler should have invoked method 'Z' at the same time.That would have ensured that there won't be any waiting time for method 'Z' to invoke to start, and we could have achieved this with  the goal of maximizing the use of CPU cycle.
In other words, this could be called concurrency or parallelism.
To achieve this, we have decorated method 'Y' as Asynchronous  using keyword 'ASYNC' and 'AWAIT' which can be applied inside it for any long running task/function. Inside the async method, one needs to call an await function. If await is not called, then compiler will think it is a synchronous call.
In the below code snippet, during execution of long running tasks in method 'Y', the compiler also invoked the method 'Z' in parallel, which ultimately has ensured that method 'Z' does not have to wait for method 'Y' completion.
Hence, message in method 'Z' printed first, although compiler invoked method 'Y' first.
  1. private static async void Y()  
  2.        {  
  3.            await Task.Delay(1000);  
  4.            for (int i = 0; i<999999999; i++)  
  5.            {  
  6.            }  
  7.            Console.WriteLine("Sync Y method called from main");  
  8.        }  
  10. private static  void Z()  
  11.        {  
  12.            Console.WriteLine("Sync Z method called from main");  
  13.        }  
  15. static void Main(string[] args)  
  16.        {  
  17.          //Although Y and Z are sequentially but Result of Z will be printed first as Y was busy in long processing.
  18.            Y();  
  19.            Z();      
  20.        }  
The output of the above code snippet is as below:
  • Sync Z method called from main 
  • Sync Y method called from main


So, we have learned the usefulness of asynchronous calling in our daily programming work.

Next Recommended Reading C# Program To Reverse A Number