I can't seem to stop the Parallel.ForEach tasks below on CTRL-C, am I not catching the exceptions correctly? I have a long running operation in a while loop.
Can anyone tell me what I'm not doing correctly here?
public static void main(string[] args)
{
CancellationTokenSource cts = new CancellationTokenSource();
StartAllReaders(cts.token)
Console.CancelKeyPress += (s,e) => {
cts.cancel();
e.cancel = true;
}
}
public static void StartAllReaders(CancellationToken cts)
{
try
{
Parallel.ForEach(
_readers,
new ParallelOptions{MaxDegreeOfParallelism=10,CancellationToken = cts},
(reader, state) =>
{
reader.Start();
while (!cts.IsCancellationRequested)
{
cts.ThrowIfCancellationRequested();
try
{
reader.ReadTelemetry();
Thread.Sleep(reader.TimeDelay);
}
catch(Exception ex)
{
//log something
continue;
}
}});
}
catch (OperationCanceledException e)
{
Logger.Info("Readers are stopping.");
}
}
I'm guessing a little bit here but I believe something like this is what you are after. It will run all the readers in parallel (with a startup delay) and cancel them when cancellation is signaled.