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
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.