Fix This async method lacks await operator warning in C#

C#.NETAsynchronous Programming

Please contribute by voting. Thanks!
1

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 Task SomeMethod()
{
    return Task.FromResult<object>(null);
}

Article created: Oct 28 '16. Edited Jan 23.

Your comment

You need to sign up / log in to comment this article

Author

Created by Matt Hamilton [8] Oct 28 '16

Share article

Do you know about

Bootstrap?

Write an article