ReSharper 2025.1 Help

Code inspection: Possibly mistaken use of a 'CancellationToken'

This inspection detects scenarios when method or function uses a CancellationToken from an external context instead of the one passed as an argument.

Incorrect usage:

public void Bar(CancellationToken methodToken) { LocalFunction(methodToken); // do something void LocalFunction(CancellationToken localFuncToken) { Foo(methodToken); // Incorrect: should use 'localFuncToken'. } } public void Foo(CancellationToken unused) => throw new Exception();

Here, LocalFunction declares a parameter CancellationToken localFuncToken, but instead of using it, the outer methodToken is passed to Foo, which might lead to inconsistent cancellation behavior.

Ensure that the token passed to the method or function is used consistently:

public void Bar(CancellationToken methodToken) { LocalFunction(methodToken); // do something void LocalFunction(CancellationToken localFuncToken) { Foo(localFuncToken); // Correct: respects the token passed to the function. } } public void Foo(CancellationToken unused) => throw new Exception();

Misusing CancellationToken can cause unexpected behavior, such as failing to cancel operations or canceling incorrectly. This inspection helps prevent these subtle bugs by enforcing consistent and correct token usage.

Last modified: 25 March 2025