CSharp Parallel Programming

Last Updated: 3/3/2022

Parallel For

Executes a for loop in which iterations may run in parallel.

Simple For

Syntax

ParallelLoopResult Parallel.For(int fromInclusive, int toExclusive, Action<int> body);

Sample

ParallelLoopResult result = Parallel.For(0, 100, index => CalculateSum(index));

For Loop with Thread Local Variables

Syntax For<TLocal>(Int32, Int32, Func<TLocal>, Func<Int32,ParallelLoopState,TLocal,TLocal>, Action<TLocal>)

Sample

int[] nums = Enumerable.Range(0, 1000000).ToArray();
long total = 0;

Parallel.For<long>(
	0,
	nums.Length,
	() => 0,
	(index, loopState, subtotal) =>
	{
    	subtotal += nums[index];
    	return subtotal;
	},
    (subtotal) => Interlocked.Add(ref total, subtotal)
);

Console.WriteLine("The total is {0:N0}", total);

Parameters

  • 0 - from value
  • nums.Length - to value
  • () => 0 - initialize thread local variable subtotal
  • (index, loopState, subtotal) => { ...} - iteration logic which updates and return subtotal
  • (subtotal) => Interlocked.Add(ref total, subtotal) - called once after all iterations on a particular thread has completed

Example