Parallel.foreach - loopState.Stop () compared to undo

What is the difference between cancel operations and loopState (Break / Stop) operation?

private static CancellationTokenSource cts;
public static loopingMethod()
{
cts = new CancellationTokenSource();
try
{
    ParallelOptions pOptions = new ParallelOptions();
    pOptions.MaxDegreeOfParallelism = 4;
    pOptions.CancellationToken = cts.Token;
    Parallel.ForEach(dictObj, pOptions, (KVP, loopState) =>
    {
        pOptions.CancellationToken.ThrowIfCancellationRequested();
        parallelDoWork(KVP.Key, KVP.Value, loopState);
     }); //End of Parallel.ForEach loop
 }
 catch (OperationCanceledException e)
 {
 //Catestrophic Failure
 return -99;
 }
}

public static void parallelDoWork(string Id, string Value, ParallelLoopState loopState)
{
   try{
      throw new exception("kill loop");
   }
   catch(exception ex)
   {
       if(ex.message == "kill loop")
       {
           cts.Cancel();
           //Or do I use loopState here?
       }
   }
}

Why do I want to use the undo operation of ParallelOptions compared to loopState.Break();or loopState.Stop();or vice versa?

+5
source share
2 answers

See article

"Setting the cancellation token allows you to cancel Invoke (remember that when a delegate throws an exception, the exception is swallowed and Invoke is called again after all other delegates have been executed )."

1. , , ex- [girl | boy]. "", . , . , , , .

2 , , , , , .

3 -, , , async/wait, parallel.foreach. Microsoft .

+2

ParallelLoopState.Break/Stop , . , , . A CancellationToken, , TPL, . , TPL, , .

+2

All Articles