CA2250: Użyj ThrowIfCancellationRequested

Właściwości Wartość
Identyfikator reguły CA2250
Tytuł Korzystanie z polecenia ThrowIfCancellationRequested
Kategoria Użycie
Poprawka powodująca niezgodność lub niezgodność Niezgodność
Domyślnie włączone na platformie .NET 8 Jako sugestia

Przyczyna

Ta reguła flaguje instrukcje warunkowe, które sprawdzają IsCancellationRequested przed zgłoszeniem OperationCanceledException.

Opis reguły

Możesz wykonać to samo, wywołując polecenie CancellationToken.ThrowIfCancellationRequested().

Jak naprawić naruszenia

Aby naprawić naruszenia, zastąp instrukcję warunkową wywołaniem metody 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

Kiedy pomijać ostrzeżenia

Można bezpiecznie pominąć ostrzeżenia z tej reguły.

Pomijanie ostrzeżenia

Jeśli chcesz po prostu pominąć pojedyncze naruszenie, dodaj dyrektywy preprocesora do pliku źródłowego, aby wyłączyć, a następnie ponownie włączyć regułę.

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

Aby wyłączyć regułę dla pliku, folderu lub projektu, ustaw jego ważność na none w pliku konfiguracji.

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

Aby uzyskać więcej informacji, zobacz Jak pominąć ostrzeżenia dotyczące analizy kodu.

Zobacz też