CA2250: ThrowIfCancellationRequested 사용

속성
규칙 ID CA2250
타이틀 ThrowIfCancellationRequested 사용
범주 사용 현황
수정 사항이 주요 변경인지 여부 주요 변경 아님
.NET 8에서 기본적으로 사용 제안 사항

원인

이 규칙은 OperationCanceledException을 throw하기 전에 IsCancellationRequested를 확인하는 조건문에 플래그를 지정합니다.

규칙 설명

CancellationToken.ThrowIfCancellationRequested()을 호출하여 동일한 작업을 수행할 수 있습니다.

위반 문제를 해결하는 방법

위반 문제를 해결하려면 조건문을 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

경고를 표시하지 않는 경우

이 규칙에서 경고를 표시하지 않아도 됩니다.

경고 표시 안 함

단일 위반만 표시하지 않으려면 원본 파일에 전처리기 지시문을 추가하여 규칙을 사용하지 않도록 설정한 후 다시 사용하도록 설정합니다.

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

파일, 폴더 또는 프로젝트에 대한 규칙을 사용하지 않도록 설정하려면 구성 파일에서 심각도를 none으로 설정합니다.

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

자세한 내용은 방법: 코드 분석 경고 표시 안 함을 참조하세요.

참고 항목