WPF TPL Restart Canceled Task

Here is my problem: I am canceling the task with a Click event that works fine. Now I want to restart the task by clicking on the same start event that originally launched the task. The β€œerror” I get is that I get MessageBox (β€œStop Clicked”) information. Therefore Im "stuck" in the Cleanup Task.

How can i solve this? Help is much appreciated.

Thanks!

Here is my code:

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(); } 
+4
source share
1 answer

Try creating a new CancellationTokenSource file and create a new token when you click the Start button.

 private void Start_Click(object sender, RoutedEventArgs e) { cts = new CancellationTokenSource(); var uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); CancellationToken token = cts.Token; ... 

From books online:

One cancellation token must refer to one "cancellation operation", however, this operation can be implemented in your program. After the IsCancellationRequested property for the token is set to true, it cannot be reset to false. Therefore, cancellation tokens cannot be reused after their cancellation.

+8
source

All Articles