Task Combinators and Cancellation
Learn how to coordinate multiple tasks using WhenAll and WhenAny, and manage task life cycles safely with CancellationToken.
We'll cover the following...
In previous lessons, we used await to wait for a single task. However, real-world applications often launch multiple operations simultaneously, such as downloading ten images, querying three different databases, or waiting for user input with a timeout.
Waiting for these tasks one by one defeats the purpose of concurrency. To handle this efficiently, C# provides task combinators: methods that combine multiple tasks into a single awaitable unit. Additionally, we need a safe way to stop these tasks if they take too long or if the user cancels the operation.
Waiting for all tasks (WhenAll)
The Task.WhenAll method accepts a collection of tasks and returns a single new task that completes only when all the provided tasks have finished. This is essential for running independent operations in parallel and waiting for the final result.