Resolve: This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run(…)’ to do CPU-bound work on a background thread.

I come across the following warning during working on one of my projects. I looked at the internet and it seems this is very common so I thought I’ll add notes to resolve it. This warning could be dangerous and result in a logical error or fairly pointless. So please bear with me to understand the concept.

CS 1998 This async method lacks ‘await’ operators and will run synchronously. Consider using the ‘await’ operator to await non-blocking API calls, or ‘await Task.Run(…)’ to do CPU-bound work on a background thread.

Reason (Why)

Commonly it happens in places where you add the async method in your interface but your code does not actually need the async method.

For example

Interface

public interface IFoo
{
    Task Test();
}

Implementation

public class Foo: IFoo
{
    public async Task Test()
    {
        if (user.Username == "test-user")
throw new Exception("can not use test user");
            
    }
}

You can see in the above example the code is not really async but the method suppose to return the result asynchronously.

So that’s why when you run this code you will get this warning. You can either ignore this warning or change your method not to return async.

You need to be very careful. You might end up removing async from your method without really analysing the rest of the code can return results asynchronously.

Solution:

You can add “Task.CompletedTask;” at the end of your task. Like below



public class Foo: IFoo
{
    public async Task Test()
    {
        if (user.Username == "test-user")
throw new Exception("can not use test user");
return Task.CompletedTask;
            
    }
}

You can suppress this warning in your project like below. If you think this is harmless

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <NoWarn>1998</NoWarn>
  </PropertyGroup>
...
</Project>

You can ignore this warning. If you think this is harmless

you can also add Do nothing by adding “await Task.Yield();”. But this is absolutely not recommended.

About the author

Naveed Ul-Haq

I am a UK based technical architect. I love working with .NET based CMS, eCommerce solutions, .NET Core, DevOps, and Cloud computing. I am a Certified Episerver CMS developer, MCSD (Microsoft Certified Solution Developer) and MCP in Azure application development. I spend my free time with my family and reading books. You can contact me on [email protected]

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *