Share via


CA2250: Gebruik ThrowIfCancellationRequested

Eigenschappen Weergegeven als
Regel-id CA2250
Titel ThrowIfCancellationRequested gebruiken
Categorie Gebruik
Oplossing is brekend of niet-brekend Niet-brekend
Standaard ingeschakeld in .NET 8 Als suggestie

Oorzaak

Deze regel markeert voorwaardelijke instructies die controleren IsCancellationRequested voordat ze worden OperationCanceledExceptiongegenereerd.

Beschrijving van regel

U kunt hetzelfde doen door aan te roepen CancellationToken.ThrowIfCancellationRequested().

Schendingen oplossen

Als u schendingen wilt oplossen, vervangt u de voorwaardelijke instructie door een aanroep naar 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

Wanneer waarschuwingen onderdrukken

Het is veilig om waarschuwingen van deze regel te onderdrukken.

Een waarschuwing onderdrukken

Als u slechts één schending wilt onderdrukken, voegt u preprocessorrichtlijnen toe aan uw bronbestand om de regel uit te schakelen en vervolgens opnieuw in te schakelen.

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

Als u de regel voor een bestand, map of project wilt uitschakelen, stelt u de ernst none ervan in op het configuratiebestand.

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

Zie Codeanalysewaarschuwingen onderdrukken voor meer informatie.

Zie ook