Skip to content

Latest commit

 

History

History
115 lines (87 loc) · 3.1 KB

File metadata and controls

115 lines (87 loc) · 3.1 KB
title description ms.date f1_keywords helpviewer_keywords author dev_langs
CA2250: Use ThrowIfCancellationRequested
Learn about code analysis rule CA2250: Use ThrowIfCancellationRequested
05/21/2021
CA2250
UseCancellationTokenThrowIfCancellationRequested
UseCancellationTokenThrowIfCancellationRequested
CA2250
NewellClark
CSharp
VB

CA2250: Use ThrowIfCancellationRequested

Property Value
Rule ID CA2250
Title Use ThrowIfCancellationRequested
Category Usage
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 As suggestion

Cause

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

Rule description

You can accomplish the same thing by calling xref:System.Threading.CancellationToken.ThrowIfCancellationRequested?displayProperty=nameWithType.

How to fix violations

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

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();
}
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.

#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.

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

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

See also