C# Interview Question #65
What is the difference between Task.WhenAll and Task.WhenAny?
Async/Await, Tasks & Multithreading Mid-Level Intermediate
Quick Interview Answer
Task.WhenAll returns a task that completes when all supplied tasks have completed. It is useful when independent asynchronous operations can run concurrently and all results are required.
Detailed Explanation
Task.WhenAll returns a task that completes when all supplied tasks have completed. It is useful when independent asynchronous operations can run concurrently and all results are required.
Task.WhenAny completes when the first supplied task completes and returns that completed task. It is useful for racing operations, timeout-style logic, or processing whichever operation finishes first.
Concurrency should only be introduced when the operations are actually independent. For example, multiple operations cannot safely run concurrently on the same EF Core DbContext instance.
Code Example
Task<User> userTask = GetUserAsync();
Task<List<Product>> productsTask = GetProductsAsync();
await Task.WhenAll(userTask, productsTask);
User user = await userTask;
List<Product> products = await productsTask;