Skip to content
C#

Async and Await

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

#async#task#concurrency

Code

csharp
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();