C# Interview Question #148

What is Parallel.ForEach, and when should it be used?

Advanced Async, Parallelism & Threading Senior Advanced

Quick Interview Answer

Parallel.ForEach executes loop iterations potentially in parallel using multiple threads. It is designed mainly for CPU-bound work where iterations are independent.

Detailed Explanation

Parallel.ForEach executes loop iterations potentially in parallel using multiple threads. It is designed mainly for CPU-bound work where iterations are independent.

It should not automatically be used for database or HTTP operations. For asynchronous I/O workloads, Task-based concurrency or Parallel.ForEachAsync may be more appropriate, with controlled concurrency.

Parallel processing should be measured because overhead and resource contention can make it slower for small workloads.

Code Example

Parallel.ForEach(numbers, number =>
{
    PerformCpuIntensiveCalculation(number);
});