다음을 통해 공유


CA2250: ThrowIfCancellationRequested 사용

속성
규칙 ID CA2250
제목 ThrowIfCancellationRequested 사용
범주 사용 현황
수정 사항이 호환성을 깨뜨리는지 여부 또는 무중단인지 여부 주요 변경 아님
.NET 10에서 기본적으로 사용하도록 설정 제안 사항
적용 가능한 언어 C# 및 Visual Basic

원인

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

규칙 설명

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

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

참고하기