簡體   English   中英

WPF TPL重新啟動已取消的任務

[英]WPF TPL Restart a canceled Task

這是我的問題:我使用Click事件取消了一個可以正常工作的任務。 現在,我想通過單擊最初啟動任務的同一啟動事件來重新啟動任務。 我得到的“錯誤”是我收到MessageBox信息(“Stop Clicked”)。 所以我“陷入”清理任務中。

我該如何解決這個問題? 非常感謝幫助。

謝謝!

這是我的代碼:

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(); }

單擊“開始”時,嘗試創建新的CancellationTokenSource並生成新的令牌。

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

從在線書籍:

一個取消令牌應該引用一個“可取消操作”,但是該操作可以在您的程序中實現。 在令牌的IsCancellationRequested屬性設置為true后,它不能重置為false。 因此,取消令牌在取消后不能重復使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM