gpt4 book ai didi

c# - WPF TPL 重新启动取消的任务

转载 作者:太空狗 更新时间:2023-10-30 00:34:35 26 4
gpt4 key购买 nike

这是我的问题:我用点击事件取消了一个工作正常的任务。现在我想通过单击最初启动任务的相同启动事件来重新启动任务。我得到的“错误”是我得到了 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 并在您单击“开始”时生成一个新的 token 。

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

来自网上的书籍:

One cancellation token should refer to one "cancelable operation," however that operation may be implemented in your program. After the IsCancellationRequested property of the token has been set to true, it cannot be reset to false. Therefore, cancellation tokens cannot be reused after they have been canceled.

关于c# - WPF TPL 重新启动取消的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7178510/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com