I have the following code that runs without throwing an exception:
var t = Task.Factory.StartNew(() => LongRunningMethod(cancellationToken, progress), cancellationToken);
t.ContinueWith(Callback, TaskScheduler.FromCurrentSynchronizationContext());
Inside ‘LongRunningMethod’, I call cancellationToken.ThrowIfCancellationRequested(). The callback will always get called (which is what I want), and the Task that gets passed to the callback correctly has IsCancelled set to true or false.
Using the async/await keywords, I have to modify the above lines to the following:
try
{
await Task.Factory.StartNew(() => LongRunningMethod(cancellationToken, progress), cancellationToken);
textEdit1.Text = "Done";
}
catch (OperationCanceledException)
{
textEdit1.Text = "Cancelled";
}
Why, in this case, does the ThrowIfCancellationRequested() throw an actual exception that I need to catch?
With
ContinueWith, you’re given theTaskthat was previously run and you can ask it if it cancelled or not (Task.IsCancelled). Withawait, you don’t have that. The only way to communicate cancel is through the exception.Now,
awaitis simply uses Tasks, so you can “interject” with a continuation. For example:You can still use await and then use
ContinueWithto handle only the cancellation scenario. so, technically theawaitis awaiting on the continuation.