CA1849: Call async methods when in an async method
Property | Value |
---|---|
Rule ID | CA1849 |
Title | Call async methods when in an async method |
Category | Performance |
Fix is breaking or non-breaking | Non-breaking |
Enabled by default in .NET 8 | No |
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.
Rule description
In a method which is already asynchronous, calls to other methods should be to their async versions, where they exist.
How to fix violations
Violation:
Task DoAsync()
{
file.Read(buffer, 0, 10);
}
Fix:
Await the async version of the method:
async Task DoAsync()
{
await file.ReadAsync(buffer, 0, 10);
}
When to suppress warnings
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.
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 CA1849
// The code that's violating the rule is on this line.
#pragma warning restore CA1849
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1849.severity = none
For more information, see How to suppress code analysis warnings.