Cancellation 操作与 loopState 操作(Break/Stop)有什么区别?
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?
}
}
}
为什么我要使用 ParallelOptions Cancellation 操作而不是loopState.Break();
反之亦然loopState.Stop();
?