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 valuenums.Length
- to value() => 0
- initialize thread local variablesubtotal
(index, loopState, subtotal) => { ...}
- iteration logic which updates and returnsubtotal
(subtotal) => Interlocked.Add(ref total, subtotal)
- called once after all iterations on a particular thread has completed