Skip to main content

MissingCancellationToken

Diagnostic Rule Overview

FieldValue
IDSHIMMER1001
Analyzer titleInclude a CancellationToken parameter in an asynchronous method
Analyzer messageAn asynchronous method is missing a CancellationToken parameter
Code fix titleAdd a CancellationToken parameter
Default severityInfo
Minimum framework/language versionN/A
CategoryShimmeringUsage
Link to codeMissingCancellationTokenAnalyzer.cs
Code fix exists?Yes

Detailed Explanation

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. Asynchronous methods that do not accept a CancellationToken limit the caller's ability to cancel the operation, causing unnecessary resource consumption. See also: https://learn.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads

Note that this diagnostic is not triggered if the method:

  1. is an override or implementation of an interface; or
  2. already has a CancellationToken parameter (either nullable or non-nullable).

Examples

Flagged code:

using System.Threading.Tasks;

namespace Tests;
class Test
{
async Task DoAsync()
{
await Task.CompletedTask;
}
}

Fixed code:

using System.Threading.Tasks;
using System.Threading;

namespace Tests;
class Test
{
async Task DoAsync(CancellationToken cancellationToken = default)
{
await Task.CompletedTask;
}
}

Justification of the Severity

In some cases, a CancellationToken parameter should not be added to an asynchronous method in some cases. See the following section.

When to Suppress

Suppress this diagnostic if:

  1. cancellation is unnecessary because the operation is quick or does not perform I/O or long-running tasks.
  2. it can cause breaking changes by breaking existing contracts
  3. it affects reflection-based code
  4. it impacts unit tests using Moq and there are too many of them
  5. the method delegates to another API without cancellation support
  6. the operation should not be cancelled based on your business logic