Parallel ForEach
- Enables data parallelism over any
IEnumerable
data source. - The loop partitions the source collection and schedules the work on multiple threads based on the system environment.
- The more processors on the system, the faster the parallel method runs
Basic Syntax
Parallel.ForEach<TSource>(IEnumerable<TSource>, Action<TSource>)
Sample
var numbers = Enumerable.Range(0, 2000000).ToList();
var primeNumbers = new ConcurrentBag<int>();
Parallel.ForEach(numbers, number => {
if(IsPrime(number))
primeNumbers.Add(number);
});
private static bool IsPrime(int number)
{
if(number < 2)
return false;
for(var divisor = 2; divisor <= Math.Sqrt(number); divisor++)
{
if(number % divisor == 0)
return false;
}
return true;
}