How to reset a CancellationToken properly?

后端 未结 2 1932
遇见更好的自我
遇见更好的自我 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:06

    I had the same problem and I figured it out that the best way to solve it is to create cancellation token source newly just before calling the method.

    this is what I do on my start button click:

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

    I change the caption for the same button to cancel and when a click occurs on cancel, I call

    cancellationTokenSource.Cancel();
    

    Here is the full code:

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

提交回复
热议问题