Fix This async method lacks await operator warning in C#

Home » Fix This async method lacks await operator warning in C#
C#

Let’s say that you need to implement an interface that contains an (async) method returning Task<T>:

public interface IGetInt {
    Task<int> GetIntAsync();
    //...
}

But you implementation lacks async operations:

public class GetInt : IGetInt {
    public async Task<int> GetIntAsync() {
        return 1;
    }
}

This will give you the following warning:

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.

An easy solution would be to use Task.FromResult() like so:

public class GetInt : IGetInt {
    public async Task<int> GetIntAsync() {
        return await Task.FromResult(1);
    }
}

And if you need to implement a method that returns only Task, this is how you can do it:

public async Task SomeMethod()
{
    return Task.FromResult<object>(null);
}

1 Comment

Should the last one be?

public async Task SomeMethod()
{
    await Task.FromResult ...
    return;
}