CA2250: Gebruik ThrowIfCancellationRequested

Eigenschap Waarde
Regel-id CA2250
Titel ThrowIfCancellationRequested gebruiken
Categorie Gebruik
Fix kan brekend of niet-brekend zijn Niet-brekend
Standaard ingeschakeld in .NET 10 Als suggestie
Toepasselijke talen C# en Visual Basic

Oorzaak

Deze regel signaleert conditionele uitspraken die IsCancellationRequested controleren voordat ze OperationCanceledException worden opgegooid.

Beschrijving van regel

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

Hoe schendingen op te lossen

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 voor meer informatie Hoe codeanalysewaarschuwingen te onderdrukken.

Zie ook