Skip to main content
All docs
V22.2

CRR0054 - Async method is called in sync context

  • 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:

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
}

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