coderushforroslyn-405453-static-code-analysis-analyzers-library-crr0054-async-method-is-called-in-sync-context.md
This analyzer identifies places where an async method is called from regular synchronous code, and the resulting task is ignored, producing a fire-and-forget[1] task:
private Task DoWorkAsync(CancellationToken token) {
// long running async operation
}
public void DoWork(CancellationToken token) {
// do something
DoWorkAsync(token); // <-- CRR0054 is reported here
// do something else
}
Private Function DoWorkAsync(ByVal token As CancellationToken) As Task
' long running async operation
End Function
Public Sub DoWork(ByVal token As CancellationToken)
' do something
' CRR0054 is reported here:
DoWorkAsync(token)
' do something else
End Sub
You can fix this warning as follows:
Add the await operator to the method call
If you do not mean the fire-and-forget behavior, add await to the method call:
private Task DoWorkAsync(CancellationToken token) {
// long running async operation
}
public async Task DoWorkAsync(CancellationToken token) {
// do something
await DoWorkAsync(token); // <-- CRR0054 is not reported here anymore
// do something else
}
Private Function DoWorkAsync(ByVal token As CancellationToken) As Task
' long running async operation
End Function
Public Async Function DoWorkAsync(ByVal token As CancellationToken) As Task
' do something
' CRR0054 is not reported here anymore:
Await DoWorkAsync(token)
' do something else
End Function
Add a discard
Assign the task returned from this call to a discard[2] if fire-and-forget behavior is intended:
private Task DoWorkAsync(CancellationToken token) {
// long running async operation
}
public void DoWork(CancellationToken token) {
// do something
_ = DoWorkAsync(token); // <-- CRR0054 is not reported here anymore
// do something else
}
Private Function DoWorkAsync(ByVal token As CancellationToken) As Task
' long running async operation
End Function
Public Sub DoWork(ByVal token As CancellationToken)
' do something
' CRR0054 is not reported here anymore due to the addition of "Dim":
Dim __ = DoWorkAsync(token)
' do something else
End Sub
Footnotes
Fire-and-forget methods in C# allow you to run a task without awaiting its completion. They are useful for executing background tasks without blocking the main application flow.
A discard in .NET (from C# 7.0 and later) is a feature that allows you to specify that you want to ignore a value that would otherwise be returned or produced by an operation, such as a method call, tuple deconstruction, or pattern matching.
See Also