Reputation: 47945
I have a Thread with this code:
foreach (string file in allDirectoriesFiles)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
// ... some operation...
}
// ... some operation 2...
notice that I use return
instead of break
, because if I stop the thread the some operation 2
must not be executed.
I also notice that in this manner the .ContinueWith it is not executed.
Well, but that is just a "return" function. How can C# know that I'm returning due to the tokenSource.Cancel()
instead of a usual return?
Upvotes: 1
Views: 4272
Reputation: 1812
You should not create the continuation with the same cancellation token or else the continuation will also be cancelled, even before it is executed. Create the continuation with a different cancellation token (from a different cancellation source) or simply create it without a cancellation token if you always want the cancellation to execute.
Upvotes: 3
Reputation: 6454
A CancellationToken is meant to propagate the cancelling to the whole set of actions at once. Once you Cancel() its source, the other continuations won't be called.
Upvotes: 1