When using Parallel.Invoke, you’re able to pass in ParallelOptions which includes a cancelationToken. Is it possible to use that token in the invocations to determine if exiting should occur? Should a reference to the CancellationTokenSource be used from within the actions?
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"); })
);
Update: The cancellation was happening too late. I was doing it outside of the invoked methods.
Note: If the cancellation happens soon enough, the Parallel.Invoke will throw, but otherwise the inoked methods will exit without fail.
Yes. For example:
In particular, you could pass the cancellation token into other methods which may propagate it to asynchronous tasks.