Asynchronous programming with C#

Ravina Deogadkar - Jan 26 '23 - - Dev Community

Asynchronous programming is an essential part of modern software development, and C# provides powerful tools for implementing it. Asynchronous programming allows developers to write code that can execute tasks concurrently, without blocking the main thread of execution. This makes applications more responsive and efficient by allowing multiple tasks to be processed at the same time.

In C#, asynchronous programming is implemented using a combination of language features such as async/await keywords and Task objects. The async keyword marks a method as being capable of running in an asynchronous context while the await keyword tells compiler that it should wait until all operations within an async method have completed before continuing with subsequent instructions in the program flow. By combining these two elements together developers can create highly performant applications which are able to process multiple requests simultaneously without waiting on any particular task or operation to complete before continuing with other work items in its queue.

To illustrate how this works let’s take a look at some sample code written using Visual Studio 2019:

public static void Main() {  

      var myTask = DoSomethingAsync();   // Start executing DoSomethingAsync(). Returns immediately!    

      Console .WriteLine("Doing something else...");     
      // Continue doing other things here...    
} 

private static async Task<int> DoSomethingAsync() {        
      int result = await LongRunningOperation();         
      return result;     
}    

private static int LongRunningOperation(){          
      Thread.Sleep(5000);           
      return 42;        
}
Enter fullscreen mode Exit fullscreen mode

In this example we start off by calling our long-running function “DoSomethingAsync” from our main entry point (Main). Notice however that when we call this function nothing actually happens because all operations within “DoSomethingAsync” are marked with ‘async' so they will run asynchronously instead – meaning they won't block or delay anything else happening inside Main(). We then print out some text indicating what's going on next ("Doing something else...") followed by finally returning control back over again once everything has finished executing inside "LongRunningOperation".

The advantage here is obvious - not only does our application remain responsive throughout but also no unnecessary resources were wasted during execution since only one thread was used for both functions even though their individual executions were performed independently from each other (in parallel). This makes asynchronous coding very effective when dealing with high volumes data processing scenarios where performance needs to be optimized accordingly

In this blog we focused on what and how's of asynchronous programing, in the next blog we will understand Task class and its methods in more detail.

Happy Coding!...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .