如何正确地重置取消令牌?

今天早上我一直在使用 Async CTP,并且有一个简单的程序,buttonlabel。单击 button,它开始更新 label,停止它停止向 label写入的 button。然而,我不知道如何重置 CancellationTokenSource,以便我可以重新启动这个过程。

我的代码:

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();
}
}
}
40937 次浏览

你需要重新创建 CancellationTokenSource-没有办法“重置”这一次,你设置它。

这可能很简单:

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

我也遇到过同样的问题,我发现解决这个问题的最好方法是在调用方法之前重新创建取消令牌源。

这就是我点击开始按钮的方式:

cancellationTokenSource = new CancellationTokenSource();
cancellationToken = cancellationTokenSource.Token;
Task.Factory.StartNew(StartUpload, cancellationToken);

我更改了要取消的同一按钮的标题,当取消时出现单击时,我调用

cancellationTokenSource.Cancel();

完整代码如下:

if (button3.Text != "&Start Upload")
{
cancellationTokenSource.Cancel();
}
else
{
try
{
cancellationTokenSource = new CancellationTokenSource();
cancellationToken = cancellationTokenSource.Token;
Task.Factory.StartNew(StartUpload, cancellationToken);
}
catch (AggregateException ex)
{
var builder = new StringBuilder();
foreach (var v in ex.InnerExceptions)
builder.Append("\r\n" + v.InnerException);
MessageBox.Show("There was an exception:\r\n" + builder.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

现在,与.NET 6,你可以使用 TryReset()方法,其中 Attempts to reset the CancellationTokenSource to be used for an unrelated operation.看到 这个问题和 Cancellationtokensource.cs的更多细节。