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