Parallel Stop and Break, parallelstopbreak
In a common for loop or foreach loop, break/continue is used for process control. In Parallel, there are also methods for process control, that is, the Stop/Break method of the ParallelLoopState class.
1. The Stop method is used to exit the Paraller loop.
See the following code:
1 var ltNum = new List <int> (); 2 for (int I = 1; I <= 10; I ++) 3 {4 ltNum. add (I); 5} 6 Parallel. for (0, ltNum. count, (I, loopState) => 7 {8 if (I> 5) 9 {10 loopState. stop (); 11 return; 12} 13 Console. writeLine ("subscript: {0}, value: {1}", I, ltNum [I]); 14 });
Among them, loopState is a ParallelLoopState class instance for parallel loop process control.
Note that row 3: loopState. Stop (); indicates that the cycle is returned immediately, regardless of whether the loop to be executed meets the I> 5 condition.
Ii. Break is used to filter loops based on conditions
If you change the code of the above 10th lines to loopState. Break ();, it means that the loop meeting the requirements of I> 5 will not be executed, but other loop bodies still need to be executed.
Note: whether it is the Break or Stop method, the return statement is required. Otherwise, the statement of the current loop body in line 13th will still be executed.
Iii. Summary
The following table compares the Stop/Break methods in Parallel with the continue/break statements in a general loop.
| ParrallelLoopState instance method |
Stop () |
Break () |
| Function |
Exit the loop. The following loop bodies are not executed. |
The loop body meeting the corresponding conditions is not executed |
| Statement equivalent to a normal Loop |
Break; |
Continue |