Skip to content

Analyzer proposal: Detect wrong CancellationToken being used when multiple tokens are available in scope #88403

@mavasani

Description

@mavasani

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.

  1. 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, say ct2, and an invocation within this lambda or local function uses ct1 instead of ct2. 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.

  2. 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 a CancellationToken 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 have CancellationToken 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions