且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

到Task.Run或不Task.Run

更新时间:2021-09-04 22:29:35

您可以完全放弃异步修改器,并使用 Task.FromResult 来同步返回一个完成的任务:

You can forgo the async modifier altogether and use Task.FromResult to return a completed task synchronously:

Task<Foo> ISomething.DoSomethingAsync()
{
    return Task.FromResult(DoSomethingElse());
}

这需要警告的关怀,具有更好的性能,因为它并不需要的的状态机的开销异步方法。

This takes care of the warning and has better performance as it doesn't need the state machine overhead of an async method.

但是,这并改变异常处理的比特的语义。如果这是一个问题,那么你应该使用同步异步法的做法并接受警告(或将其关闭了评论):

However, this does change the semantics of exception handling a bit. If that's an issue then you should use the synchronous async method approach and accept the warning (or turn it off with a comment):

#pragma warning disable 1998
    async Task<Foo> ISomething.DoSomethingAsync() 
#pragma warning restore 1998
    {
        return DoSomethingElse();
    }

由于斯蒂芬·克利建议你也可以采取警告护理(同时保持同步的方法),通过在等待一个已经完成的任务:

As Stephen Cleary suggested you can also take care of that warning (while keeping the method synchronous) by awaiting an already completed task:

async Task<Foo> ISomething.DoSomethingAsync() 
{
    await Task.FromResult(false); // or Task.CompletedTask in .Net 4.6
    return DoSomethingElse();
}