CSharp Parallel Programming

Last Updated: 3/8/2022

Parallel ForEach

  • Enables data parallelism over any IEnumerabledata 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;
}

Example