I have the following code :
CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
Task.Factory.StartNew(() =>
{
if (Console.ReadKey().KeyChar == 'c')
cts.Cancel();
Console.WriteLine("press any key to exit");
});
Parallel.ForEach(list, po, (algo) =>
{
algo.Compute(); // this compute lasts 1 minute
Console.WriteLine("this job is finished");
po.CancellationToken.ThrowIfCancellationRequested();
});
The list
contains few elements.
All the Compute
methods have already been started when I press 'c'.
When I press 'c', no exception is thrown. Each Compute
methods continues its execution until its normal end.
I would like to stop/kill all the remain Compute
methods when I press 'c'.