ParallelLoopState::Break Method ()

.NET Framework (current version)
 

Communicates that the Parallel loop should cease execution of iterations beyond the current iteration at the system's earliest convenience.

Namespace:   System.Threading.Tasks
Assembly:  mscorlib (in mscorlib.dll)

public:
void Break()

Exception Condition
InvalidOperationException

The Stop method was previously called. Break and Stop may not be used in combination by iterations of the same loop.

Break indicates that no iterations after the current iteration should be run. It effectively cancels any additional iterations of the loop. However, it does not stop any iterations that have already begun execution. For example, if Break is called from the 100th iteration of a parallel loop iterating from 0 to 1,000, all iterations less than 100 should still be run, but the iterations from 101 through to 1000 that have not yet started are not executed.

For long-running iterations that may already be executing, Break sets the LowestBreakIteration property to the current iteration's index if the current index is less than the current value of LowestBreakIteration. To stop iterations whose index is greater than the lowest break iteration from competing execution, you should do the following:

  1. Check whether the ShouldExitCurrentIteration property is true.

  2. Exit from the iteration if its index is greater than the LowestBreakIteration property value.

The example provides an illustration.

Break is typically employed in search-based algorithms where an ordering is present in the data source.

The following example executes up to 100 iterations of a loop in parallel. Each iteration pauses for a random interval from 1 to 1,000 milliseconds. A randomly generated value determines on which iteration of the loop the Break method is called. As the output from the example shows, no iterations whose index is greater than the LowestBreakIteration property value start after the call to the Break method.

No code example is currently available or this language may not be supported.

Because iterations of the loop are still likely to be executing when the Break method is called, each iteration calls the ShouldExitCurrentIteration property to check whether another iteration has called the Break method. If the property value is true, the iteration checks the value of the LowestBreakIteration property and, if it is greater than the current iteration's index value, returns immediately.

Universal Windows Platform
Available since 8
.NET Framework
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Windows Phone
Available since 8.1
Return to top
Show: