Part 04 of a hands-on C# practice series (01 collections, 02 LINQ, 03 delegates & events). Seven runnable, heavily commented examples covering the most-asked advanced C# topic: what await really does, WhenAll concurrency, where async exceptions go, CancellationToken, the famous .Result deadlock, CPU-bound vs I/O-bound, and IAsyncEnumerable streams. Timestamped + thread-id output ([ 123 ms | t 4]) lets you see threads being freed and work overlapping.
dotnet run # all examples
dotnet run 5 # just one (e.g. deadlocks)| # | Topic | Highlights |
|---|---|---|
| 01 | Tasks & await basics | thread ids across awaits, hot tasks, state machine, async void |
| 02 | Sequential vs concurrent | 300 ms → 120 ms with WhenAll, WhenAny, as-they-complete loop |
| 03 | Exceptions | throw-at-await, fire-and-forget swallowing, WhenAll + AggregateException |
| 04 | CancellationToken | CancelAfter, manual cancel, linked tokens, cooperative model |
| 05 | Deadlocks | anatomy of .Result deadlock, ConfigureAwait(false), thread starvation |
| 06 | CPU-bound | Task.Run, Parallel.ForEach + Interlocked, Parallel.ForEachAsync throttle |
| 07 | IAsyncEnumerable | await foreach, streaming vs Task<List<T>>, [EnumeratorCancellation] |
awaitfrees the thread — it never blocks one.- Start tasks first,
await Task.WhenAll(...)together — durations stop adding up. - Never block on async (
.Result/.Wait()); go async all the way toMain. - Pass a
CancellationTokenthrough every async API you write. - I/O-bound →
await. CPU-bound →Task.Run/Parallel. Don't mix them up.
- Asynchronous programming (C# guide)
- Task-based asynchronous pattern
- ConfigureAwait FAQ (Stephen Toub)
← Previous: 03 Delegates & events · Next: 05 Generics →
| Part | Topic |
|---|---|
| 01 | Collections |
| 02 | LINQ |
| 03 | Delegates & events |
| 04 | Async/await (this repo) |
| 05 | Generics |
| 06 | Types & memory |
| 07 | Exceptions |
| 08 | Modern C# 8–12 |
| 09 | Strings & text |
| 10 | Files & JSON |
| 11 | MiniShop microservices (finale) |
Matej Zlatunić
Released under the MIT License. Feel free to use it for learning.