How to reset a CancellationToken properly?

后端 未结 2 1934
遇见更好的自我
遇见更好的自我 2020-12-09 01:42

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<

2条回答
  •  被撕碎了的回忆
    2020-12-09 02:11

    You need to recreate the CancellationTokenSource - there is no way to "reset" this once you set it.

    This could be as simple as:

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

提交回复
热议问题