Parallel.Invokeを使用する場合、cancellationTokenを含むParallelOptionsを渡すことができます。呼び出しでそのトークンを使用して、終了する必要があるかどうかを判断することは可能ですか?アクション内からCancellationTokenSourceへの参照を使用する必要がありますか?
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
Parallel.Invoke(po,
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 1"); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 2"); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 3"); cts.Cancel(); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 4"); }),
new Action(() => { if (cts.IsCancellationRequested) return; Console.WriteLine("Invoked Method 5"); })
);
更新:キャンセルは遅すぎました。呼び出されたメソッドの外でそれを行っていました。
注:キャンセルがすぐに発生した場合、Parallel.Invokeはスローされますが、それ以外の場合、呼び出されたメソッドは必ず終了します。