Examples of Async and Await in C#

Simple Async Method Example

This example demonstrates an asynchronous method that simulates a delay using Task.Delay.

Code Example:

public async Task SimpleDelayAsync()
{
    Console.WriteLine("Task starting...");
    await Task.Delay(2000);
    Console.WriteLine("Task completed after 2 seconds.");
}

// Usage
await SimpleDelayAsync();
        

Fetching Data Asynchronously

This example demonstrates how to fetch data from a web API asynchronously using HttpClient.

Code Example:

public async Task FetchDataAsync(string url)
{
    using (HttpClient client = new HttpClient())
    {
        var response = await client.GetStringAsync(url);
        return response;
    }
}

// Usage
string data = await FetchDataAsync("https://api.example.com/data");
Console.WriteLine(data);
        

Handling Exceptions in Async Methods

This example demonstrates handling exceptions in an asynchronous method.

Code Example:

public async Task SafeFetchDataAsync(string url)
{
    try
    {
        string data = await FetchDataAsync(url);
        Console.WriteLine(data);
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine($"Request error: {e.Message}");
    }
}

// Usage
await SafeFetchDataAsync("https://api.example.com/data");
        

Running Multiple Tasks in Parallel

This example demonstrates how to run multiple asynchronous tasks concurrently using Task.WhenAll.

Code Example:

public async Task RunMultipleTasksAsync()
{
    Task task1 = Task.Delay(2000);
    Task task2 = Task.Delay(3000);
    Task task3 = Task.Delay(1000);
    
    await Task.WhenAll(task1, task2, task3);
    Console.WriteLine("All tasks completed.");
}

// Usage
await RunMultipleTasksAsync();
        

Using ConfigureAwait(false)

This example demonstrates how to use ConfigureAwait(false) to avoid deadlocks in UI applications.

Code Example:

public async Task FetchDataWithConfigureAwaitAsync(string url)
{
    using HttpClient client = new HttpClient();
    return await client.GetStringAsync(url).ConfigureAwait(false);
}

// Usage
string data = await FetchDataWithConfigureAwaitAsync("https://api.example.com/data");
Console.WriteLine(data);
        
Previous: Introduction to Async & Await