Reading the outcome of parallel loops in .NET C#
June 11, 2014 1 Comment
The Parallel.For() and Parallel.ForEach() methods both return a ParallelLoopResult object. This object has two properties which you can use to read if Break or Stop have been called:
- IsCompleted: true if all loop iterations have been completed without calling either Break or Stop
- LowestBreakIteration: the index of the lowest iteration in which the Break method was called
Example:
ParallelLoopResult parallelLoopResult = Parallel.For(0, 10, (int index, ParallelLoopState parallelLoopState) => { if (index == 5) { parallelLoopState.Stop(); } }); Console.WriteLine("IsCompleted: {0}", parallelLoopResult.IsCompleted); Console.WriteLine("BreakValue: {0}", parallelLoopResult.LowestBreakIteration.HasValue? parallelLoopResult.LowestBreakIteration.Value : -1);
The properties return the following values:
IsCompleted (IC): false
LowestBreakIteration.HasValue (LBI): false
Here come the possible value pairs and their meaning:
- IC true, LBI false: all iterations were completed without breaking or stopping
- IC false, LBI false: Stop was called
- IF false, LBI true: Break was called
View the list of posts on the Task Parallel Library here.
Thanks!!