C#C#
AdvancedLesson 12 of 16

async/await & Tasks – C#

Concurrent I/O without blocked threads.

async/await lets you wait for slow operations (network, files, database) without blocking the thread. An async method returns Task or Task<T>; await pauses the method until the result is available. With Task.WhenAll, several tasks run at the same time.

var ergebnisse = await Task.WhenAll(
    HoleAsync("A", 1000),
    HoleAsync("B", 2000),
    HoleAsync("C", 1000));

foreach (var e in ergebnisse)
    Console.WriteLine(e);
// takes about 2 seconds instead of 4

static async Task<string> HoleAsync(string name, int ms)
{
    await Task.Delay(ms);
    return $"{name} done after {ms} ms";
}

A typical use case is HttpClient. Create the client once and reuse it instead of building a new one for every request.

using System.Text.Json;

using var client = new HttpClient();
client.DefaultRequestHeaders.UserAgent.ParseAdd("ProgrammAtlas");

string json = await client.GetStringAsync("https://api.github.com/repos/dotnet/runtime");
using var doc = JsonDocument.Parse(json);
Console.WriteLine(doc.RootElement.GetProperty("full_name").GetString());

You cancel running operations cooperatively with a CancellationToken. Data streams that deliver values bit by bit are modeled with IAsyncEnumerable<T> and await foreach:

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2));
try
{
    await Task.Delay(5000, cts.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("Cancelled");
}

await foreach (var zahl in ZaehleAsync(3))
    Console.WriteLine(zahl);   // 1 2 3

static async IAsyncEnumerable<int> ZaehleAsync(int n)
{
    for (int i = 1; i <= n; i++)
    {
        await Task.Delay(100);
        yield return i;
    }
}
WarningNever block on a task with .Result or .Wait() – in UI or ASP.NET contexts this risks deadlocks. Use await "all the way up". async void is intended only for event handlers, because errors from it cannot be caught.
Tipasync does not make code faster, it makes waiting more efficient. For compute-intensive work, use Task.Run or Parallel.ForEach.