Should I worry about “This async method lacks 'await' operators and will run synchronously” warning

后端 未结 5 1119
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-30 01:18

I have a interface which exposes some async methods. More specifically it has methods defined which return either Task or Task. I am using the async/await keywords.

5条回答
  •  情深已故
    2020-11-30 01:38

    The async keyword is merely an implementation detail of a method; it isn't part of the method signature. If one particular method implementation or override has nothing to await, then just omit the async keyword and return a completed task using Task.FromResult:

    public Task Foo()               //    public async Task Foo()
    {                                       //    {
        Baz();                              //        Baz();
        return Task.FromResult("Hello");    //        return "Hello";
    }                                       //    }
    

    If your method returns Task instead of Task, then you can return a completed task of any type and value. Task.FromResult(0) seems to be a popular choice:

    public Task Bar()                       //    public async Task Bar()
    {                                       //    {
        Baz();                              //        Baz();
        return Task.FromResult(0);          //
    }                                       //    }
    

    Or, as of .NET Framework 4.6, you can return Task.CompletedTask:

    public Task Bar()                       //    public async Task Bar()
    {                                       //    {
        Baz();                              //        Baz();
        return Task.CompletedTask;          //
    }                                       //    }
    

提交回复
热议问题