Here’s my problem: I cancel a Task with a Click Event which works fine. Now I want to restart the Task by clicking on the same start event which started the Task initially. The “error” that I get is that I get the MessageBox Information (“Stop Clicked”). So I’m “stuck” in the Cleanup Task.
How do I solve this? Help is very much appreciated.
谢谢!
我的守则如下:
public partial class MainWindow
{ CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
}
private void Start_Click(object sender, RoutedEventArgs e)
{ var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
CancellationToken token = cts.Token;
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
Task dlTask = Task.Factory.StartNew(() =>
{ do
{ token.ThrowIfCancellationRequested();
Parallel.For(0, dicQueryNoQueryURL.Count, po
, i =>
{ token.ThrowIfCancellationRequested();
if (!token.IsCancellationRequested){// do work
}
});
}
while (!token.IsCancellationRequested);
}, token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
dlTask.ContinueWith(
(antecedents) =>
{ if (token.IsCancellationRequested){
MessageBox.Show("Stop Clicked");
}
else
{ MessageBox.Show("Signalling production end"); }
dlTask.Dispose();
}, uiScheduler);
}
private void btnStop_Click(object sender, RoutedEventArgs e){ cts.Cancel(); }