Race condition with CancellationToken where CancellationTokenSource is only cancelled on the main thread

后端 未结 2 705
北恋
北恋 2021-01-06 07:41

Consider a Winforms application, where we have a button that generates some results. If the user presses the button a second time, it should cancel the first request to gen

2条回答
  •  清酒与你
    2021-01-06 08:30

    The way I see it, regardless of which thread checks the CencellationToken, you have to consider the possibility that your continuation can get scheduled and the user can cancel the request while the continuation is being executed. So I think the check that was commented out should be checked and should probably be checked AGAIN after reading the result:

            task.ContinueWith(t =>
        {
            // Is this code necessary to prevent a race condition?
            if (ct.IsCancellationRequested)
                return;
    
            int result = t.Result;
    
            if (ct.IsCancellationRequested)
                return;
    
            m_label.Text = result.ToString();
        }, ct, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());
    

    I would also add a continutation to handle the cancellation condition separately:

            task.ContinueWith(t =>
        {
            // Do whatever is appropriate here.
    
        }, ct, TaskContinuationOptions.OnlyOnCanceled, TaskScheduler.FromCurrentSynchronizationContext());
    

    This way you have all possibilities covered.

提交回复
热议问题