We have used constructs such as break and continue in sequential loops; break is used to break out of a loop by finishing the current iteration and skipping the rest, whereas continue skips the current iteration and moves to the rest of the iterations. These constructs can be used because the sequential loops are executed by a single thread. In the case of parallel loops, we cannot use the break and continue keywords since they run on multiple threads or tasks. To break a parallel loop, we need to make use of the ParallelLoopState class. To cancel a loop, we need to make use of the CancellationToken and ParallelOptions classes.
In this section, we will discuss the options that you require to cancel loops:
- Parallel.Break
- ParallelLoopState.Stop
- CancellationToken
Let's get started!