← Zurück zum Kurs: C# from scratch

Asynchronous programming with async and await

Video folgt in Kürze

Some operations take time: reading a large file, requesting data from a server, querying a database. If your program just waits doing nothing else, a windowed application freezes and a server handles fewer requests. Asynchronous programming solves this: instead of blocking, the program starts the operation, frees the thread to do other things and resumes the work when the result is ready. C# makes it simple with two keywords, async and await, that let you write asynchronous code almost the same as normal code.

Task, async and await

An asynchronous method is marked with async and returns Task (if it produces no value) or Task<T> (if it produces a value of type T). By convention its name ends in Async. Inside, the word await waits for another asynchronous operation to finish without blocking the thread and, when it completes, delivers its result. A Task represents work in progress that will finish in the future. In a program with top-level statements you can use await directly, without needing a special Main method. The .NET methods that may take time usually have an Async version, such as File.ReadAllTextAsync or Task.Delay, which is the way to "wait" without freezing anything.

csharp
Console.WriteLine("Start");
string greeting = await GetGreetingAsync("Ana");
Console.WriteLine(greeting);                       // Hello, Ana!

string path = Path.Combine(Path.GetTempPath(), "async-demo.txt");
await File.WriteAllTextAsync(path, "Saved without blocking");
string text = await File.ReadAllTextAsync(path);
Console.WriteLine(text);                           // Saved without blocking
Console.WriteLine("End");

async Task<string> GetGreetingAsync(string name)
{
    await Task.Delay(500);                         // simulates a slow operation
    return $"Hello, {name}!";
}

Running several tasks at once

If you await three one-second tasks one after another, you take three seconds. But if they are independent you can start them all first and wait for all together with Task.WhenAll, and the total will be about one second. That is the great practical advantage: combining several waits. Task.WhenAll returns an array with the results in the same order in which you passed the tasks, and if any fails, the exception is thrown when you await. A Stopwatch timer helps you measure it and check it with your own eyes.

csharp
using System.Diagnostics;

var watch = Stopwatch.StartNew();
string a = await FetchAsync("A");
string b = await FetchAsync("B");
Console.WriteLine($"Sequential: {a}{b} in about {watch.Elapsed.TotalSeconds:0} s");  // about 2 s

watch.Restart();
string[] results = await Task.WhenAll(FetchAsync("A"), FetchAsync("B"), FetchAsync("C"));
Console.WriteLine($"Parallel: {string.Join("", results)} in about {watch.Elapsed.TotalSeconds:0} s"); // ABC, about 1 s

try
{
    await FailAsync();
}
catch (InvalidOperationException ex)
{
    Console.WriteLine($"Caught: {ex.Message}");            // Caught: Something broke
}

async Task<string> FetchAsync(string name)
{
    await Task.Delay(1000);
    return name;
}

async Task FailAsync()
{
    await Task.Delay(10);
    throw new InvalidOperationException("Something broke");
}

Teste dein Wissen

Frage 1 von 2

What does an async method that produces a string return?

✎ Meine Notizen

Nur in diesem Browser gespeichert. Melde dich an, um es im Konto zu behalten.0/5000 Zeichen

← ZurückWeiter →