Back to Devexpress

CRR0054 - Async method is called in sync context

coderushforroslyn-405453-static-code-analysis-analyzers-library-crr0054-async-method-is-called-in-sync-context.md

latest3.1 KB
Original Source

CRR0054 - Async method is called in sync context

  • May 21, 2025
  • 2 minutes to read

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:

csharp
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
}
vb
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:

csharp
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
}
vb
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:

csharp
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
}
vb
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

  1. 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.

  2. 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

Suppress Analyzers