user9393635
user9393635

Reputation: 1429

how extensively should the async/await pattern be used?

I came across the following comment on SO:

"Also use of the async await pattern with newer versions of .Net will give the efficiencies closer to that of the event-driven architectures like NodeJS and Nginx"

I inherited a Web API app where basically all methods in all layers leverage the async/await pattern. The comment above about the performance of async/await is pretty compelling. Is it proper to implement async/await on all methods of all layers in a Web API app? Are there any scenarios where I should avoid await/async or be careful to not overuse it?

Upvotes: 1

Views: 586

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456537

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.

Upvotes: 6

Related Questions