C#idiomatic C#
ca2250fundamentals/code-analysis/quality-rules

Code analysis

CA2250: Use `ThrowIfCancellationRequested`

Learn about code analysis rule CA2250: Use ThrowIfCancellationRequested

CA2250 Usage enabled by default in .NET 10: As suggestion
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

This rule flags conditional statements that check System.Threading.CancellationToken.IsCancellationRequested before throwing System.OperationCanceledException.

Rule description

You can accomplish the same thing by calling System.Threading.CancellationToken.ThrowIfCancellationRequested.

How to fix violations

To fix violations, replace the conditional statement with a call to System.Threading.CancellationToken.ThrowIfCancellationRequested.

csharp
using System;
using System.Threading;

public void MySlowMethod(CancellationToken token)
{
    // Violation
    if (token.IsCancellationRequested)
        throw new OperationCanceledException();

    // Fix
    token.ThrowIfCancellationRequested();

    // Violation
    if (token.IsCancellationRequested)
        throw new OperationCanceledException();
    else
        DoSomethingElse();

    // Fix
    token.ThrowIfCancellationRequested();
    DoSomethingElse();
}
vb
Imports System
Imports System.Threading

Public Sub MySlowMethod(token As CancellationToken)

    ' Violation
    If token.IsCancellationRequested Then
        Throw New OperationCanceledException()
    End If

    ' Fix
    token.ThrowIfCancellationRequested()

    ' Violation
    If token.IsCancellationRequested Then
        Throw New OperationCanceledException()
    Else
        DoSomethingElse()
    End If

    ' Fix
    token.ThrowIfCancellationRequested()
    DoSomethingElse()
End Sub

When to suppress warnings

It is safe to suppress warnings from this rule.

Suppress a warning

If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

csharp
#pragma warning disable CA2250
// The code that's violating the rule is on this line.
#pragma warning restore CA2250

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

ini
[*.{cs,vb}]
dotnet_diagnostic.CA2250.severity = none

For more information, see How to suppress code analysis warnings.

See also