Call async methods when in an async method
Prefer awaiting async APIs over their blocking counterparts.
Microsoft docsDescription
Within an async method, prefer the asynchronous version of an API instead of a blocking call that ties up a thread.
Cause
All methods where an Async-suffixed equivalent exists will produce this warning when called from a Task-returning method. In addition, calling Task.Wait(), Task<T>.Result, or Task.GetAwaiter().GetResult() will produce this warning.
Why it matters
Blocking calls inside async methods waste threads and can cause thread-pool starvation.
How to fix violations
Violation:
Fix:
Await the async version of the method:
Examples
async Task Save()
{
stream.Write(buffer);
}async Task Save()
{
await stream.WriteAsync(buffer);
}When to suppress
It's safe to suppress a warning from this rule in the case where there are two separate code paths for sync and async code, using an if condition. Also if there is a check for whether the Task has resolved, it is safe to use sync methods and properties.