sonar-dotnet icon indicating copy to clipboard operation
sonar-dotnet copied to clipboard

New Rule Idea: Don't use ConfigureAwait in ASP.NET Core applications

Open zsolt-kolbay-sonarsource opened this issue 1 year ago • 0 comments

TITLE Don't use ConfigureAwait in ASP.NET Core applications

WHY IS THIS AN ISSUE ASP.NET Core does not have a Synchronization Context. Using ConfigureAwait(false) in an ASP.NET Core application is redundant and can be misleading. The main reason for using ConfigureAwait(false) is to improve performance and prevent deadlocks by avoiding returning to the original context (such as a UI thread in a WPF application). However, since there's no Synchronization Context in ASP.NET Core, there's no context to marshal back to, and therefore, no need for ConfigureAwait(false).

Nevertheless, using ConfigureAwait(false) can still be beneficial in other contexts like:

  • legacy ASP.NET applications (running on the .NET Framework instead of .NET Core / .NET)
  • UI applications such as WPF
  • class libraries (because we can't know which application will reference it)

NONCOMPLIANT CODE EXAMPLE

[ApiController]
[Route("api/[controller]")]
public class SampleController : ControllerBase
{
    ...

    [HttpGet]
    public IEnumerable<UserData> GetDataAsync(int dataId)
    {
        return await ReadDataAsync(dataId).ConfigureAwait(false); // Noncompliant
    }
}

COMPLIANT CODE EXAMPLE

[ApiController]
[Route("api/[controller]")]
public class SampleController : ControllerBase
{
    ...

    [HttpGet]
    public IEnumerable<UserData> GetDataAsync(int dataId)
    {
        return await ReadDataAsync(dataId); // Compliant
    }
}

ANALYZER IMPLEMENTATION

Look for invocations of Task.ConfigureAwait() (it doesn't matter whether it's called with true or false as argument) and raise a warning for each. A CodeFix is easy to implement for this rule, all it needs to do is remove the invocation. The analyzer should only be active in ASP.NET Core projects, it shouldn't raise in .NET Framework projects or non-ASP.NET projects.

RESOURCES

  • https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html
  • https://stackoverflow.com/questions/42053135/configureawaitfalse-relevant-in-asp-net-core
  • https://devblogs.microsoft.com/dotnet/configureawait-faq/#ive-heard-configureawaitfalse-is-no-longer-necessary-in-net-core-true (Note: this shows a counter-example when this rule shouldn't be used. But I believe it's a rare scenario, and if that's the case the developers can simply disable the rule.)