异步:return 任务或先在 asp.net webapi 中等待

async: return task or await first in asp.net webapi

你好我有一个关于 webapi 的 async/await 的小问题。这两种用法之间有区别吗?哪一种被认为是正确的?阅读后 SimilarQuestion on SO 我猜变体 1 更好,因为开销更少,但我需要确定,因此我再次询问;)

变体 1:

public Task<string> Get(){
    return Bar();
}

变体 2:

public async Task<string> Get(){
    return await Bar();
}

方法:

public async Task<string> Foo(){
    await Task.Delay(5000);
    return "Done";
}

public Task Bar(){
    return Foo();
}

感谢提示

变体 2 是不可能的,因为你做不到

public async Task<string> Get(){
    return await Bar();
}

public Task Bar(){
    return Foo();
}

await 仅适用于 asyncTask Bar() 不是 async... 它只是 Task.

看看Can I not await for async Task without making it async void? 它说

The correct way to handle this is to await the method, and make the calling method async Task. This will have a cascading effect as async travels up through your code.

话虽如此,您只剩下变体 1。对于大多数情况,这是一个不错的选择。如果您觉得 async await 会对性能产生负面影响,那么您可能将错误的方法设置为 async。但同样,您需要对其进行校准。不可能有一个解决所有方法的通用答案。

另见:

  1. the-overhead-of-asyncawait-in-net-4.5
  2. Behind the .NET 4.5 Async Scene: The performance impact of Asynchronous programming in C#