Skip to content
C#

Async and Await

Run I/O concurrently with async methods, await, and Task.WhenAll.

By EZ4Code Team
asynctaskconcurrency

Code

using System;
using System.Net.Http;
using System.Threading.Tasks;

HttpClient client = new();

async Task<string> FetchAsync(string url, CancellationToken ct = default)
{
    using var resp = await client.GetAsync(url, ct);
    resp.EnsureSuccessStatusCode();
    return await resp.Content.ReadAsStringAsync(ct);
}

async Task RunAsync()
{
    try
    {
        var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
        // Run requests in parallel
        var tasks = new[]
        {
            FetchAsync("https://api.github.com", cts.Token),
            FetchAsync("https://httpbin.org/get", cts.Token),
        };
        string[] results = await Task.WhenAll(tasks);
        Console.WriteLine($"got {results.Length} responses");
    }
    catch (HttpRequestException ex)
    {
        Console.Error.WriteLine($"HTTP error: {ex.Message}");
    }
}

await RunAsync();

Explanation

async marks a method as one that can await other async operations, returning a Task that represents the in-flight work. await suspends the method without blocking the thread, yielding control back to the caller until the awaited task completes. Task.WhenAll composes multiple tasks so they run concurrently and waits for all of them together.

More C# Snippets