Task.WhenAll vs Parallel.ForEach
Question Variations
- "When would you use `Task.WhenAll` versus `Parallel.ForEach`?"
- "Explain the difference between I/O-bound and CPU-bound operations in the context of .NET."
- "What is 'thread pool starvation,' and how can using `Parallel.ForEach` for I/O-bound work cause it?"
- "What is `Parallel.ForEachAsync`, and when was it introduced in the .NET ecosystem?"
Why This Is Asked
This distinguishes developers who understand the difference between I/O concurrency and CPU parallelism. Interviewers want to see if you can pick the right tool — async for I/O-bound work, parallel for CPU-bound work — and avoid thread pool starvation.
Key Concepts
Task.WhenAll: I/O concurrency — coordinates multiple async operations, does not necessarily use extra threadsParallel.ForEach: CPU parallelism — partitions data across threads for compute-heavy workParallel.ForEachAsync(.NET 6+): hybrid — async I/O with controlled concurrency viaMaxDegreeOfParallelism- Using
Parallel.ForEachfor I/O-bound work blocks threads and leads to thread pool starvation - Shared state in parallel operations requires thread-safe collections or explicit locking
Question Variations
- “When would you use
Task.WhenAllversusParallel.ForEach?” - “Explain the difference between I/O-bound and CPU-bound operations in the context of .NET.”
- “What is ‘thread pool starvation,’ and how can using
Parallel.ForEachfor I/O-bound work cause it?” - “What is
Parallel.ForEachAsync, and when was it introduced in the .NET ecosystem?”