NashTech Insights

Asynchronous Programming in C# with async/await in .NET

Picture of Tushar Dhiman
Tushar Dhiman
Table of Contents
C# async/await Image.

Introduction

In the world of building computer programs, it’s important to make sure our code runs quickly and efficiently. Let’s say we are constructing a building, and we want it to finish it as soon as possible. To achieve this every worker must do their work parallelly. So, in the same manner in world of computer programming we want our instructions in a code to get executed parallelly and to achieve this we use asynchronous programming. It’s like having different tasks being done at the same time, allowing our code to run smoothly and do not get stuck while waiting for one thing to finish before moving on to the next. 

What is Asynchronous Programming? 

Think of it as giving our builders the ability to work on different parts of the building simultaneously. While one group is working on the foundation, another can be putting up walls, making things happen faster overall. 

So, in technical terms asynchronous programming enables a program to perform multiple operations at the same time without waiting for each one to complete before moving on to the next. This is particularly useful for tasks that might take some time to finish, such as reading data from a file, making a network request, or performing complex calculations. 

Some key concepts related to asynchronous programming: 

  1. Concurrency:Asynchronous programming provides concurrency, which means that different parts of a program can run simultaneously. 
  1. Non-Blocking Operations:Instead of blocking the program’s execution while waiting for a task to complete, asynchronous programming allows the program to continue with other tasks by running them on different threads. 
  1. Callbacks:We use callbacks with Asynchronous code to delegate tasks which specify what should happen when a task completes. This helps in defining the behavior which will be applied to the code after the completion of an asynchronous operation. 

Asynchronous Programming in C# 

Async function in C#: 

When a method is marked as ‘async’, it gains the ability to run tasks in the background which means on the different thread instead running it on the main thread. In this way it does not block the main thread from executing the other tasks which makes our code or program responsive and efficient. 

async Task DoSomethingAsync() {
// Asynchronous tasks can happen here
}

Await keyword:

Await keyword is like a friendly assistant that helps the async function to get the things done. When our method encounters an operation that might take some time, like fetching data from the internet, it can use ‘await’ to delegate the task to the background (on different thread) and continue with the other tasks on the main thread.  

async Task<string> GetDataAsync() {
  // Some time-consuming operation, like fetching data
  // The 'await' keyword lets the method continue with other tasks while waiting for this to finish 
  string result = await FetchDataFromInternetAsync();
  // Once the data is ready, the method continues here
  return result;
}

Example in C# using async and await

using System;
using System.Threading.Tasks;

class Program
{
  static async Task Main()
  {
    Console.WriteLine("Main method start.");

    // Start asynchronous operation
    Task<string> asyncOperation = PerformAsyncOperation();

    // Continue with other work while waiting for the asynchronous operation
    for (int i = 1; i <= 5; i++)
    {
      Console.WriteLine($"Main method doing other work {i}.");
      await Task.Delay(500);
    }

    // Wait for the asynchronous operation to complete
    string result = await asyncOperation;

    Console.WriteLine($"Main method end. Result from async operation: {result}"); 
  }

  static async Task<string> PerformAsyncOperation()
  {
    Console.WriteLine("Async operation start.");

    // Simulate an asynchronous operation with Task.Delay
    await Task.Delay(3000);

    Console.WriteLine("Async operation end.");

    // Return a result
    return "Async operation result";
  }
}

OUTPUT:

Image not available.

Code Explanation

In the Main method, we start by printing “Main method start.” to the console. Then, we do an asynchronous operation by calling the PerformAsyncOperation method, which simulates some time-consuming task (in this case, waiting for 3 seconds using Task.Delay). While waiting for this asynchronous operation to complete, the Main method continues with other work, printing “Main method doing other work [number]” to the console five times with a delay of 500 milliseconds between each iteration.

Once the asynchronous operation is complete, we retrieve the result and print “Main method end. Result from async operation: [result]” to the console.

The PerformAsyncOperation method also uses async and await. It starts by printing “Async operation start.” to the console, then simulates some work with Task.Delay. After the delay, it prints “Async operation end.” and returns “Async operation result”.

References

https://learn.microsoft.com/en-us/dotnet/csharp/

 

Recommended Reads

Effortless Log Integration with Dynatrace

Introduction to Websockets.

Understanding API.

Picture of Tushar Dhiman

Tushar Dhiman

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article