I'm running a foreach and I would like to cancel its execution on a key press.
While I succeeded doing it integrating a single if (keypress) within the loop, now I'm trying to achieve the same using a CancellationToken while the task for listening for a key stroke is running.
var ts = new CancellationTokenSource();
CancellationToken ct = ts.Token;
Task.Factory.StartNew(() =>
{
while (true)
{
foreach (var station in stations)
{
/*if (Console.KeyAvailable)
{
break;
}*/
Console.WriteLine(station.name + " ");
Thread.Sleep(100);
}
Thread.Sleep(100);
if (ct.IsCancellationRequested)
{
// another thread decided to cancel
Console.WriteLine("task canceled");
break;
}
}
}, ct);
ts.Cancel();
Console.ReadLine();
I came from this answer How do I abort/cancel TPL Tasks? which helped me a lot.
However, while it works without the foreach, right now the foreach has to end before the task is cancelled.
Obviously, it looks like the iteration has to end before proceeding to the next step and what I don't understand is how I can make the foreach stop.
