What is difference between loopstate.Break(), loopState.Stop() and CancellationTokenSource.Cancel()

牧云@^-^@ 提交于 2019-12-30 03:55:07

问题


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();

                }
            }
        });

回答1:


CancellationToken is used to signal cancellation.

loopState.Break() and loopState.Stop() are used to end execution.

Here's an example

Parallel.For(0, maximum_operations, options, (a, loopState) =>
    {
        // do work

        // cancellationToken.Cancel() should be called externally
        if(token.IsCancellationRequested)
        {
            // cancellation requested - perform cleanup work if necessary

            // then call
            loopState.Break();
            // or
            loopState.Stop();
        }
    });

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 OperationCanceledException exception:

public void MyMethod()
{
    try
    {
        Parallel.For(0, maximum_operations, options, (a, loopState) =>
        {
            // do work

            token.ThrowIfCancellationRequested();
        });
    }
    catch (OperationCanceledException)
    {
        // handle cancellation
    }
}

All of these methods are valid ways to terminate execution of Parallel.For. Which one you use depends on your requirements.

For example:

  • Is it essential to immediately stop all execution when your windows Service is stopped? Then you could use token.ThrowIfCancellationRequested()
  • Does your loop deal with IDisposable objects that need cleanup? Then you could use loopState.Break() or loopState.Stop()

Some articles for reference:

  • MSDN: Cancellation
  • MSDN: How to: Stop or Break from a Parallel.For Loop


来源:https://stackoverflow.com/questions/8818203/what-is-difference-between-loopstate-break-loopstate-stop-and-cancellationt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!