I have a simple question, i have following simple Parallel for loop. this for loop is part of windows service. I want to stop the loop, when someone stops the service. I can find three ways to stop parallel for, which is in if condition. What is the best way of stopping the parallel for loop and what are the differences?
CancellationTokenSource cancellationToken = new CancellationTokenSource();
ParallelOptions options = new ParallelOptions();
options.CancellationToken = cancellationToken.Token;
Parallel.For(0, maximum_operations, options, (a, loopState) =>
{
{
//Do something
if(!KeepProcessing)
{
//loopState.Break();
//loopState.Stop();
cancellationToken.Cancel();
}
}
});
CancellationTokenis used to signal cancellation.loopState.Break()andloopState.Stop()are used to end execution.Here’s an example
loopState.Break()means complete all iterations on all threads that are prior to the current iteration on the current thread, and then exit the loop (MSDN).loopState.Stop()means stop all iterations as soon as convenient (MSDN).Another way to terminate execution is call token.ThrowIfCancellationRequested(), but you will need to handle the
OperationCanceledExceptionexception:All of these methods are valid ways to terminate execution of
Parallel.For. Which one you use depends on your requirements.For example:
token.ThrowIfCancellationRequested()loopState.Break()orloopState.Stop()Some articles for reference: