nested Parallel.For Loop - Cancellation.Token doesn't work
I have the following problem: I have a tight loop (on purpose) which starts on a click event in the MainWindow.cs of my WPF application.
Now, a stop event triggered by another button should stop the tight loop and end the Task.
In my tight loop I have a Parallel.For
loop.The idea is that I have to do a certain amount of things simultaneously (Parallel.For) and this over and over again (tight loop). I don't know if this is the best approach but it's the only one that I had, however it works :) .
I have a problem with the Cancellation.Token which doesn’t seem to do anything. How do I stop the loop and end the Task correctly.
Here’s my code:
var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
CancellationToken token = cts.Token;
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParall开发者_高级运维elism = System.Environment.ProcessorCount;
Task dlTask = Task.Factory.StartNew(
() =>
{
do
{
Parallel.For(0, num, po, i => {
if (!token.IsCancellationRequested)
{
// do work
}
});
}
while (!token.IsCancellationRequested);
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
dlTask.ContinueWith(prev =>
{
//clean up
}, uiScheduler);
I tried it with po.CancellationToken.IsCancellationRequested
and without and it didn't stop.
private void btnStop_Click(object sender, RoutedEventArgs e)
{
if (cts.IsCancellationRequested || po.CancellationToken.IsCancellationRequested)
{
cts.Cancel();
}
}
UPDATE: Solution thanks to Damien_The_Unbeliever:
private void btnStop_Click(object sender, RoutedEventArgs e)
{
cts.Cancel();
}
You need to call cts.Cancel() in the event handler for your stop button. This will tell your cancelation token that you have requested cancellation.
精彩评论