Language
Edit

CA2027: Cancel Task.Delay after Task.WhenAny completes

Property Value
Rule ID CA2027
Title Cancel Task.Delay after Task.WhenAny completes
Category Reliability
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 10 No
Enabled by default in .NET 11 As suggestion
Applicable languages C# and Visual Basic

Cause

A call to WhenAny includes a Delay call that doesn't accept a CancellationToken.

Rule description

When another task completes first, a noncancelable delay continues to run until its timeout expires. The unused timer consumes resources.

How to fix violations

If you only need to wait for an operation with a timeout, use Task.WaitAsync(TimeSpan). It throws a TimeoutException if the operation doesn't complete before the timeout.

If you need to call Task.WhenAny, pass a cancellation token to Task.Delay and cancel the token source when the other task completes.

Examples

The following code shows a violation of CA2027:

Task winner = await Task.WhenAny(operation, Task.Delay(timeout));
Dim winner = Await Task.WhenAny(operation, Task.Delay(timeout))

Use Task.WaitAsync when you only need a timeout:

await operation.WaitAsync(timeout);
Await operation.WaitAsync(timeout)

Or cancel the delay after Task.WhenAny returns:

using var cts = new CancellationTokenSource();
Task winner = await Task.WhenAny(operation, Task.Delay(timeout, cts.Token));
cts.Cancel();
Using cts As New CancellationTokenSource()
    Dim winner = Await Task.WhenAny(operation, Task.Delay(timeout, cts.Token))
    cts.Cancel()
End Using

When to suppress warnings

Suppress the warning only when the delay should continue after another task completes.

Suppress a warning

To suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.

#pragma warning disable CA2027
// The code that's violating the rule is on this line.
#pragma warning restore CA2027

To disable the rule for a file, folder, or project, set its severity to none in the configuration file.

[*.{cs,vb}]
dotnet_diagnostic.CA2027.severity = none

For more information, see How to suppress code analysis warnings.

See also