如何正确重置CancellationToken? [英] How to reset a CancellationToken properly?
本文介绍了如何正确重置CancellationToken?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
今天早上,我一直在与异步CTP
一起玩,并且有一个带有按钮
的简单程序标签
。单击按钮
,它开始更新标签
,停止按钮
它将停止写入标签
。但是,我不确定如何重置 CancellationTokenSource
以便重新启动该过程。
I have been playing round with the Async CTP
this morning and have a simple program with a button
and a label
. Click the button
and it starts updating the label
, stop the button
it stops writing to the label
. However, I'm not sure how to reset the CancellationTokenSource
so that I can restart the process.
我的代码:
public partial class MainWindow : Window
{
CancellationTokenSource cts = new CancellationTokenSource();
public MainWindow()
{
InitializeComponent();
button.Content = "Start";
}
async Task DoWork(CancellationToken cancelToken)
{
int i = 0;
while (!cancelToken.IsCancellationRequested)
{
label.Content = i++.ToString();
await TaskEx.Delay(50, cancelToken);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (button.Content == "Start")
{
button.Content = "Stop";
DoWork(cts.Token);
}
else
{
button.Content = "Start";
cts.Cancel();
}
}
}
推荐答案
您需要重新创建 CancellationTokenSource
-一旦设置,便无法对其进行重置。
You need to recreate the CancellationTokenSource
- there is no way to "reset" this once you set it.
这可能很简单:
private void Button_Click(object sender, RoutedEventArgs e)
{
if (button.Content == "Start")
{
button.Content = "Stop";
cts.Dispose(); // Clean up old token source....
cts = new CancellationTokenSource(); // "Reset" the cancellation token source...
DoWork(cts.Token);
}
else
{
button.Content = "Start";
cts.Cancel();
}
}
这篇关于如何正确重置CancellationToken?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文