What is async and await in C#

In C#, async and await are keywords used to perform asynchronous programming, enabling developers to write code that can run concurrently without blocking the main thread. This is particularly useful for improving the performance of applications, especially during I/O-bound operations like network calls or file access.

When a method is marked with the async modifier, it can contain one or more await expressions. These expressions will allow the program to pause execution of that method until the awaited task completes, freeing up the main thread to execute other work in the meantime.


public async Task FetchDataAsync()
{
    using (HttpClient client = new HttpClient())
    {
        // Await the asynchronous call
        var response = await client.GetStringAsync("https://api.example.com/data");
        // Process the response
        return response;
    }
}
    

async await C# asynchronous programming performance improvement I/O-bound operations