async / await模式应该使用多大?

时间:2018-04-20 00:12:06

标签: c# .net asp.net-web-api async-await asp.net-web-api2

我在SO上发现了以下评论:

"同样使用async await模式和更新版本的.Net将使效率更接近NodeJS和Nginx等事件驱动架构的效率。

我继承了一个Web API应用程序,基本上所有层中的所有方法都利用了async / await模式。以上关于async / await性能的评论非常引人注目。在Web API应用程序中的所有层的所有方法上实现async / await是否合适?是否有任何情况我应该避免等待/异步或小心不要过度使用它?

1 个答案:

答案 0 :(得分:6)

I recommend reading my intro to async on ASP.NET article.

Is it proper to implement async/await on all methods of all layers in a Web API app?

Yes. In fact, it's imperative. async really only works (in terms of providing the benefits you get from async) if you use it all the way. So, if your implementation calls another API asynchronously, then that method should be consumed asynchronously, etc., all the way up to your initial controller action.

In particular, you want to avoid sync-over-async antipatterns.

Are there any scenarios where I should avoid await/async or be careful to not overuse it?

Yes. You should avoid "fake async". This is the antipattern where a developer uses Task.Run (or similar) in order to get a task so they can "use async". It often looks like this:

int GetId() { ... }
Task<int> GetIdAsync() => Task.Run(() => GetId());
...
var id = await GetIdAsync(); // Look, I'm async! (not really)

In this case, the code is hurting your scalability rather than helping it.