C#idiomatic C#
ca2261fundamentals/code-analysis/quality-rules

Code analysis

CA2261: Do not use `ConfigureAwaitOptions.SuppressThrowing` with `Task<TResult>`

Learn about code analysis rule CA2261 - Do not use `ConfigureAwaitOptions.SuppressThrowing` with `Task<TResult>`

CA2261 Usage enabled by default in .NET 10: As warning
Fix is breaking or non-breaking Non-breakingApplicable languages C# and Visual Basic

Cause

A value of System.Threading.Tasks.ConfigureAwaitOptions.SuppressThrowing is passed to System.Threading.Tasks.Task.ConfigureAwait(System.Threading.Tasks.ConfigureAwaitOptions).

Rule description

The System.Threading.Tasks.ConfigureAwaitOptions.SuppressThrowing option isn't supported by the generic System.Threading.Tasks.Task, since that might lead to returning an invalid TResult. This rule flags the use of System.Threading.Tasks.ConfigureAwaitOptions.SuppressThrowing with System.Threading.Tasks.Task to surface the error at build time rather than runtime.

How to fix violations

Cast the System.Threading.Tasks.Task to a non-generic System.Threading.Tasks.Task before calling System.Threading.Tasks.Task.ConfigureAwait(System.Threading.Tasks.ConfigureAwaitOptions).

Example

The following code snippet shows a violation of CA2261:

csharp
Task<int> t = new Task<int>(() => 1);
t.ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);

The following code snippet shows the fix:

csharp
Task<int> t = new Task<int>(() => 1);
((Task)t).ConfigureAwait(ConfigureAwaitOptions.SuppressThrowing);

When to suppress errors

You shouldn't suppress warnings from this rule. If the task is faulted or canceled, TResult will be invalid and cause runtime errors.