Share via


CA2250: Använd ThrowIfCancellationRequested

Property Värde
Regel-ID CA2250
Title Använda ThrowIfCancellationRequested
Kategori Användning
Korrigeringen är icke-bakåtkompatibel Icke-icke-bryta
Aktiverad som standard i .NET 8 Som förslag

Orsak

Den här regeln flaggar villkorssatser som kontrollerar IsCancellationRequested innan du genererar OperationCanceledException.

Regelbeskrivning

Du kan göra samma sak genom att anropa CancellationToken.ThrowIfCancellationRequested().

Så här åtgärdar du överträdelser

Om du vill åtgärda överträdelser ersätter du villkorssatsen med ett anrop till 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

När du ska ignorera varningar

Det är säkert att ignorera varningar från den här regeln.

Ignorera en varning

Om du bara vill förhindra en enda överträdelse lägger du till förprocessordirektiv i källfilen för att inaktivera och aktiverar sedan regeln igen.

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

Om du vill inaktivera regeln för en fil, mapp eller ett projekt anger du dess allvarlighetsgrad till none i konfigurationsfilen.

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

Mer information finns i Så här utelämnar du kodanalysvarningar.

Se även