title | description | ms.date | f1_keywords | helpviewer_keywords | author | dev_langs | ||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
CA2250: Use ThrowIfCancellationRequested |
Learn about code analysis rule CA2250: Use ThrowIfCancellationRequested |
05/21/2021 |
|
|
NewellClark |
|
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 |
This rule flags conditional statements that check xref:System.Threading.CancellationToken.IsCancellationRequested before throwing xref:System.OperationCanceledException.
You can accomplish the same thing by calling xref:System.Threading.CancellationToken.ThrowIfCancellationRequested?displayProperty=nameWithType.
To fix violations, replace the conditional statement with a call to xref: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 Sub
It is safe to suppress warnings from this rule.
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.