Async and Await: Waiting Without Blocking
Learn Task, async and await, run several slow operations at once with Task.WhenAll, cancel work, handle task errors, and see from real timings that concurrent waiting beats sequential waiting.
In this lesson you will
- Write async methods with await
- Run tasks concurrently with WhenAll
- Cancel a task
- Handle exceptions from tasks
About 28 minutes
Five suppliers, one phone call each
Omar needs the stock level from five suppliers, and each answer takes a fifth of a second to arrive. If the program asks them one after another, the total wait is five times as long as it needs to be, and while it waits nothing else can happen. Most of the time a program spends in this kind of work is waiting for something else: a network, a disk, a database. Async programming lets the program start a request and do other work, or start the next request, while the answer is on its way.
A Task represents work that will finish later, and may produce a value, as Task does. A method marked async can use await, which pauses that method until a task finishes, without blocking the thread, and then continues with the result. Because the first request does not need to finish before the second one starts, you can start all five and then await them together with Task.WhenAll. Note that this is concurrency, not parallel computation: while the program waits, the processor is free. For work that is heavy computation, tasks on several threads, with Task.Run or Parallel.For, are the tool. A CancellationToken lets a caller ask a running task to stop, and an exception thrown inside a task surfaces when you await it.
| Tool | Use it for |
|---|---|
| async / await | Writing waiting code that reads like normal code |
| Task.Delay | Waiting without blocking, also used here to simulate slow work |
| Task.WhenAll | Starting several tasks and waiting for all of them |
| CancellationToken | Asking a task to stop |
| Task.Run | Moving CPU-heavy work to a pool thread |
using System.Diagnostics;
async Task<int> AskSupplier(int id)
{
await Task.Delay(200);
return id * id;
}
var sw = Stopwatch.StartNew();
int seqTotal = 0;
for (int i = 0; i < 5; i++) seqTotal += await AskSupplier(i);
long seqMs = sw.ElapsedMilliseconds;
sw.Restart();
int[] results = await Task.WhenAll(Enumerable.Range(0, 5).Select(AskSupplier));
long conMs = sw.ElapsedMilliseconds;
Console.WriteLine($"sequential total {seqTotal}, concurrent results {string.Join(",", results)} (sum {results.Sum()})");
Console.WriteLine($"sequential took at least 1000 ms: {seqMs >= 1000}");
Console.WriteLine($"concurrent took under 500 ms: {conMs < 500}, and at least 200 ms: {conMs >= 200}");
async Task Failing() { await Task.Delay(10); throw new InvalidOperationException("supplier 3 is closed"); }
try { await Task.WhenAll(Failing(), AskSupplier(1)); }
catch (InvalidOperationException e) { Console.WriteLine($"error surfaced at await: {e.Message}"); }
using var cts = new CancellationTokenSource(100);
try { await Task.Delay(5000, cts.Token); Console.WriteLine("finished"); }
catch (OperationCanceledException) { Console.WriteLine("cancelled after about 100 ms instead of waiting 5000 ms"); }
int fib = await Task.Run(() => { int a = 0, b = 1; for (int i = 0; i < 30; i++) (a, b) = (b, a + b); return a; });
Console.WriteLine($"Task.Run computed fib(30) = {fib}");
sequential total 30, concurrent results 0,1,4,9,16 (sum 30)
sequential took at least 1000 ms: True
concurrent took under 500 ms: True, and at least 200 ms: True
error surfaced at await: supplier 3 is closed
cancelled after about 100 ms instead of waiting 5000 ms
Task.Run computed fib(30) = 832040
Both ways produced the same answers: the squares 0, 1, 4, 9, 16, which add up to 30. The difference is the waiting. Asking one supplier after another took at least a full second, as five waits of 200 ms add up to 1000 ms, and the concurrent version started all five at once and finished in a little over one wait, under half a second. Timings vary with the machine, so the program prints only comparisons that hold with a wide margin, and not the exact milliseconds.
The next test shows error handling. One of two concurrent tasks threw, and the exception came out at the await, as an ordinary InvalidOperationException, with the message of the failing task, so a normal try and catch works for async code. The cancellation test asked a five-second wait to stop after 100 milliseconds, and the task ended with an OperationCanceledException at once instead of waiting. Finally Task.Run moved a small computation to a pool thread and brought the answer back with await: the thirtieth Fibonacci number, 832040.
Check by hand: 0 + 1 + 4 + 9 + 16 = 30. Five waits of 200 ms give 1000 ms in a row, and 200 ms when they overlap. Python computed the thirtieth Fibonacci number independently and also gave 832040.
Calling .Result or .Wait() on a task from code that could await it can freeze programs that have a main thread, such as desktop apps. Use await all the way up.
To overlap waiting, create all the tasks before awaiting them, then use WhenAll. Awaiting each one as you create it makes the work sequential again.
Every program in this lesson was built and run with the .NET 8 SDK and C# 12 while the course was written. .NET and C# release every year, so check the official Microsoft documentation for the current version and for features added after .NET 8.
Practice
Write an async method that downloads the length of several local files concurrently, using File.ReadAllTextAsync. Add a timeout with a CancellationTokenSource, and check by hand which files were read and in what order they finished.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What does await do?
- Blocks the whole program
- Starts a new process
- Pauses the method until the task finishes, without blocking the thread
- Deletes the task
The method resumes with the result.
Why was the concurrent version faster?
- The computer was faster
- The five waits overlapped
- The tasks did less work
- Await skips waiting
Waiting, not computing, was the bottleneck.
What does Task.WhenAll return?
- The first result only
- A task that completes when all given tasks complete
- Nothing
- A thread
Await it to get the results.
Where does an exception inside a task appear?
- At the await
- Never
- At compile time
- In another program
A normal try and catch handles it.
How can you stop a long wait?
- Use a CancellationToken
- Close the editor
- Restart Windows
- Use Console.Clear
The task ends with OperationCanceledException.
Summary
- async and await let code wait without blocking.
- Task.WhenAll overlaps independent waits.
- Exceptions in tasks surface at the await.
- CancellationToken stops running work.
Questions
Is async the same as multithreading?
No. Async lets code wait without blocking. Tasks may run on the same thread or on pool threads. CPU-heavy work benefits from threads.
What does async void mean?
A method that returns nothing and cannot be awaited. Avoid it except for event handlers, because its errors are hard to catch.
What is ConfigureAwait?
An option that affects which context a method resumes on. It matters in libraries and some app types. See the documentation.
