Lesson 21 of 24
In progress
async and await
Write asynchronous code that does not block, avoid async void and .Result, and understand what await actually waits for.
Most programs spend their time waiting: for a disk, a network, a database. Asynchronous code lets the thread do something else during that wait instead of sitting blocked.
What you will learn
- Mark a method
asyncandawaitaTask. - Avoid the two classic mistakes:
async voidand.Result. - Run independent operations concurrently.
The shape
using System.Net.Http;
static async Task<string> FetchAsync(string url)
{
using var client = new HttpClient();
string body = await client.GetStringAsync(url);
return body.Length.ToString();
}
string result = await FetchAsync("https://example.com");
Console.WriteLine(result);
async marks the method as one that may await. Task<string> is the return type: a promise of a string. await suspends the method until the task completes, then continues with the value.
The thread is released while waiting, which is the point. In a console app there is little else to do, but in a server a released thread can serve another request, and that is what keeps throughput up under load.
Return types
Task— completes with no value.Task<T>— completes with aT.ValueTask<T>— likeTask<T>with less allocation when it often completes synchronously.void— only for event handlers, never for your own methods.
async void cannot be awaited and its exceptions cannot be caught by the caller; they surface on the synchronisation context and often crash the process. Use async Task everywhere else.
The blocking trap
// wrong in most contexts
string body = FetchAsync(url).Result;
Blocking on a task with .Result or .Wait() can deadlock: the method continues on a context that the blocked thread is holding. In a console app it usually works, in a UI app it freezes, and in ASP.NET Core it may work until it does not. Await all the way up instead.
string body = await FetchAsync(url);
If a synchronous caller cannot await, the fix is usually to make the caller asynchronous too, not to block lower down.
Concurrency
var urls = new[] { "https://example.com", "https://example.org" };
var tasks = urls.Select(url => FetchAsync(url));
string[] results = await Task.WhenAll(tasks);
Task.WhenAll starts all the operations and waits for the last. Sequential awaits would take the sum of the durations; WhenAll takes the longest, which is the difference between a slow page and a fast one when several independent calls are needed.
var first = await Task.WhenAny(tasks);
WhenAny completes with the first finished task, which is useful for timeouts and racing mirrors.
Errors
try
{
await FetchAsync(url);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"request failed: {ex.Message}");
}
An awaited task throws at the await, so normal try/catch works. With Task.WhenAll, the exception is the first one, and task.Exception on each task holds the details if you need all of them.
An unobserved task exception — one that is never awaited — is silently dropped in modern .NET, which is another reason to always await or explicitly handle.
Cancellation
static async Task<string> FetchAsync(string url, CancellationToken token)
{
using var client = new HttpClient();
return await client.GetStringAsync(url, token);
}
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
await FetchAsync("https://example.com", cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("timed out");
}
A CancellationToken lets a caller stop work that is no longer needed, which matters for timeouts and for requests whose client has disconnected. Pass it through to the APIs that accept one; checking it manually is a fallback, not a substitute.
ConfigureAwait
Library code often writes .ConfigureAwait(false):
var data = await reader.ReadToEndAsync().ConfigureAwait(false);
That tells the runtime not to resume on the captured context, which avoids a deadlock risk and a small overhead. Application code with a UI does not need it; library code should use it. In ASP.NET Core there is no synchronisation context, so it makes little difference.
Async streams
await foreach (var line in ReadLinesAsync(path))
{
Console.WriteLine(line);
}
static async IAsyncEnumerable<string> ReadLinesAsync(string path)
{
using var reader = new StreamReader(path);
while (await reader.ReadLineAsync() is { } line)
{
yield return line;
}
}
IAsyncEnumerable<T> is the asynchronous counterpart of a sequence: each element arrives when it is ready, without buffering the whole set.
When not to use async
CPU-bound work does not become faster with async; it needs a background thread (Task.Run) or parallelism. Async is for I/O waits. Adding async to a method that only computes adds state-machine overhead and no benefit.
Using async void for a method you want to await. The caller cannot wait for it, and an exception inside it can terminate the process. Use async Task.
Fetch two URLs concurrently, print both lengths, and apply a five-second timeout to the whole operation.
Show solution
using var client = new HttpClient(); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5)); var tasks = new[] { client.GetStringAsync("https://example.com", cts.Token), client.GetStringAsync("https://example.org", cts.Token) }; try { var bodies = await Task.WhenAll(tasks); foreach (var body in bodies) { Console.WriteLine(body.Length); } } catch (OperationCanceledException) { Console.WriteLine("timed out"); } Both requests start before the first await, so they run concurrently and the total time is the slower of the two. The shared token cancels both when the timeout fires, and the catch turns that into a message instead of a crash.
Recap
async Task/Task<T>plusawaitfrees the thread during I/O waits.- Never block with
.Result; useTask.WhenAllfor independent work and pass aCancellationToken. - Async is for waiting, not for CPU work, and
async voidis only for event handlers.
Module 5 builds something: a console app, a minimal web API, a test and a capstone.
Should every method be async?
What does await actually do?
Progress is saved in this browser only. No account, no email.