如何正确重置CancellationToken?

时间:2012-02-17 17:11:15

标签: c# asynchronous async-await cancellationtokensource cancellation-token

我今天早上一直在玩async ctp,并且有一个简单的程序buttonlabel。点击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();
        }
    }
}

2 个答案:

答案 0 :(得分:61)

您需要重新创建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();
    }
}

答案 1 :(得分:6)

即使我遇到同样的问题,我也知道,解决问题的最佳方法是在调用方法之前新创建取消令牌源。

这就是我在开始按钮上点击的内容:

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