문제

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top