CA2250: Use ThrowIfCancellationRequested
Property | Value |
---|---|
Rule ID | CA2250 |
Title | Use ThrowIfCancellationRequested |
Category | Usage |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 8 | As suggestion |
Cause
This rule flags conditional statements that check IsCancellationRequested before throwing OperationCanceledException.
Rule description
You can accomplish the same thing by calling CancellationToken.ThrowIfCancellationRequested().
How to fix violations
To fix violations, replace the conditional statement with a call to 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
When 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 CA2250
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA2250.severity = none
For more information, see How to suppress code analysis warnings.