C# Tutorial: Async/Await
Write asynchronous code with async/await, Task, Task<T>, and understand the threading model.
Asynchronous programming
`async/await` allows writing asynchronous code that reads like synchronous code.
It is essential for I/O-bound operations: network requests, file reads, database queries — anything that waits for external resources.
What you'll learn in this C# async/await tutorial
This interactive C# tutorial has 8 hands-on exercises. Estimated time: 22 minutes.
- Basic async method — An `async` method can use `await`. It returns `Task` (void) or `Task<T>` (value).
- Returning Task<T> — Async methods returning a value use `Task<T>`.
- async void — `async void` is for event handlers. Avoid it in other code — exceptions cannot be caught.
- Task.WhenAll — parallel tasks — Run multiple async operations in parallel with `Task.WhenAll`.
- Task.WhenAny — first wins — `Task.WhenAny` returns when the FIRST task completes.
- CancellationToken — Pass a `CancellationToken` to cancel long-running operations.
- ValueTask for hot paths — `ValueTask<T>` avoids heap allocation when the result is often synchronously available.
- Async streams — `IAsyncEnumerable<T>` is async foreach — items arrive over time.
C# Async/Await concepts covered
- Asynchronous programming