All rules
CA2250Usage Enabled by default: As suggestion

Use ThrowIfCancellationRequested

Use ThrowIfCancellationRequested

Microsoft docs

Description

ThrowIfCancellationRequested automatically checks whether the token has been canceled, and throws an OperationCanceledException if it has.

Cause

This rule flags conditional statements that check System.Threading.CancellationToken.IsCancellationRequested before throwing System.OperationCanceledException.

How to fix violations

To fix violations, replace the conditional statement with a call to System.Threading.CancellationToken.ThrowIfCancellationRequested.

Example

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();
}

When to suppress

It is safe to suppress warnings from this rule.

Group results
0 yes 0 no
ConsensusNone (disabled)
Severity preference (yes voters)
Suggestion0
Warning0
Error0