69

今天早上我一直在玩,Async CTP并且有一个带有 abutton和 a的简单程序label。单击button它开始更新label,停止button它停止写入label. 但是,我不确定如何重置,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();
        }
    }
}
4

3 回答 3

99

您需要重新创建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();
    }
}
于 2012-02-17T17:17:44.373 回答
9

我遇到了同样的问题,我发现解决它的最佳方法是在调用该方法之前新创建取消令牌源。

这就是我点击开始按钮时所做的:

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);
    }
}
于 2013-12-04T07:05:31.323 回答
3

现在,使用 .NET 6,您可以使用查看问题的TryReset()方法和CancellationTokenSource.cs了解更多详细信息。Attempts to reset the CancellationTokenSource to be used for an unrelated operation.

于 2021-09-07T08:59:39.407 回答