Cause
This rule flags conditional statements that check System.Threading.CancellationToken.IsCancellationRequested before throwing System.OperationCanceledException.
Rule description
You can accomplish the same thing by calling System.Threading.CancellationToken.ThrowIfCancellationRequested.
How to fix violations
To fix violations, replace the conditional statement with a call to System.Threading.CancellationToken.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 SubWhen to suppress warnings
It is safe to suppress warnings from this rule.
Suppress a warning
If you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA2250
// The code that's violating the rule is on this line.
#pragma warning restore CA2250To disable the rule for a file, folder, or project, set its severity to none in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA2250.severity = noneFor more information, see How to suppress code analysis warnings.