Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top