CA2012: Use ValueTasks correctly

Property Value
Rule ID CA2012
Title Use ValueTasks correctly
Category Reliability
Fix is breaking or non-breaking Non-breaking
Enabled by default in .NET 8 As suggestion

Cause

A ValueTask instance returned from a member invocation is used in a way that could lead to exceptions, corruption, or poor performance.

Rule description

ValueTask instances returned from member invocations are intended to be directly awaited. Attempts to consume a ValueTask multiple times or to directly access one's result before it's known to be completed may result in an exception or corruption. Ignoring such a ValueTask is likely an indication of a functional bug and may degrade performance.

How to fix violations

In general, ValueTasks should be directly awaited rather than discarded or stored into other locations like local variables or fields.

When to suppress warnings

For ValueTask objects returned from arbitrary member calls, the caller needs to assume that the ValueTask must be consumed (for example, awaited) once and only once. However, if the developer also controls the member being invoked and has complete knowledge of its implementation, the developer may know it's safe to suppress the warning, for example, if the return ValueTask always wraps a Task object.

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 CA2012
// The code that's violating the rule is on this line.
#pragma warning restore CA2012

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

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

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

See also