CA2012: Use ValueTasks correctly

Value
Rule ID CA2012
Category Reliability
Fix is breaking or non-breaking Non-breaking

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 ValueTasks returned from arbitrary member calls, the caller needs to assume that the ValueTask must be consumed (e.g. 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.

See also