Asynchronous Programming with Async and Await in C#

Using C#, asynchronous programming is achieved using the async and await keywords. Asynchronous programming in C# is particularly useful for tasks that involve I/O operations, such as reading from or writing to files, making web requests, or interacting with databases.

How async and await work in C#?

Here's an overview of how async and await work in C#.

Asynchronous Methods

You define asynchronous methods using the async modifier. An asynchronous method usually returns a Task or Task<T> to represent the ongoing operation.

using System.Threading.Tasks;

public class MyClass
{
    public async Task MyAsyncMethod()
    {
        // Asynchronous code here
        await Task.Delay(1000); // Simulating an asynchronous operation
        // Continue with more code
    }
}

await Keyword

The await keyword is used inside an asynchronous method to asynchronously wait for the completion of a task without blocking the execution of the program.

Task-Based Asynchronous Pattern (TAP)

The Task Parallel Library (TPL) in C# provides the Task-based Asynchronous Pattern. Asynchronous methods return Task or Task<T> objects, which represent asynchronous operations.

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        await DoAsyncWork();
        Console.WriteLine("Main method completed.");
    }

    static async Task DoAsyncWork()
    {
        Console.WriteLine("Async method started.");
        await Task.Delay(2000);
        Console.WriteLine("Async method completed.");
    }
}

Async Main Method (C# 7.1 and later)

Starting from C# 7.1, you can use the async modifier in the Main method.

using System;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("Main method started.");
        await DoAsyncWork();
        Console.WriteLine("Main method completed.");
    }

    static async Task DoAsyncWork()
    {
        Console.WriteLine("Async method started.");
        await Task.Delay(2000);
        Console.WriteLine("Async method completed.");
    }
}

These features make it easier to write asynchronous code in C# and improve the responsiveness of applications by allowing them to perform other tasks while waiting for asynchronous operations to complete.


Recommended Free Ebook
Similar Articles