Analyzer proposal: Detect wrong CancellationToken being used when multiple tokens are available in scope #88403
Labels
api-suggestion
Early API idea and discussion, it is NOT ready for implementation
area-System.Threading
code-analyzer
Marks an issue that suggests a Roslyn analyzer
feature-request
Milestone
Issue #33774 was used to implement the rule CA2016 (Forward the CancellationToken parameter to methods that take one), via PR dotnet/roslyn-analyzers#3641. This rule flags invocations where cancellation token wasn't being passed, when one was available in the context of the invocation.
I'd like to propose either an extension to this rule or a new rule to detect when the wrong cancellation token is being passed, when multiple tokens are available in scope.
Pattern 1: For example, an async method that takes a cancellation token parameter, say
ct1
, defines a lambda or a local function that takes another cancellation token parameter, sayct2
, and an invocation within this lambda or local function usesct1
instead ofct2
. This inevitably indicates a functional bug. We were bitten by this very recently in Roslyn - see Thread in the correct cancellation token into the code action operation roslyn#68859, and using the wrong cancellation token in a code fixer led to a very subtle, hard to diagnose bug.Pattern 2: Another pattern that we may want to consider to detect is when a type defines a field of type
CancellationToken
and also has an async method that takes aCancellationToken
parameter, and an invocation within this method uses the cancellation token field instead of the parameter. This pattern may or may not indicate a bug, but still definitely indicates code smell and bad design - it should be recommended to either always haveCancellationToken
be a method parameter OR a field, but not both within the same type.Proposed category: Reliability
Proposed severity: IDE suggestion
Code fixer: Should be trivial to implement
The text was updated successfully, but these errors were encountered: