Task Combinators and Cancellation
Explore how to manage multiple asynchronous tasks effectively using task combinators like WhenAll and WhenAny in C#. Learn to implement cooperative cancellation with CancellationToken and enforce timeouts using WaitAsync for responsive and controllable asynchronous programming.
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 ...