Is Async/Await necessary for every controller actions?

Tanul 1,251 Reputation points
2021-11-14T20:06:03.733+00:00

Team,

I have seen multiple c# projects in different organizations and everyone has a strict habit of decorating actions of controller as async/await with returning type as Task<IActionResult> .

Is this the recommendation by Microsoft? Can anyone suggest the reason behind doing this in rest api or azure function etc. Why defining this has become a habit for a C# engineer.

Can anyone share the advantages and disadvantages of this approach. Thank you.

Regards

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,187 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,275 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,686 Reputation points
    2021-11-14T22:59:54.69+00:00

    the old asp.net created a thread per request, but this was not the most performant. Asp.net core only creates a thread per core. While this is less threads, performing async operations free the thread to do other work. This give asp.net core more than an order (10x) performance increase.

    In practice this means actions (or razor pages models) should always use the async version of a library call, or if heavy compute bound, create a thread for the computation. all network, file and database calls are async by nature. you should never use the sync version or the sync helper .Result.

    note: node.js which is single threaded, but uses an async pipeline was much more performant than asp.net. Core followed this model (even using the node.js pipeline code - which has been replaced) but creates a separate pipeline thread per cpu.

    the reason for this design is because context switches between threads, while cheaper than a process switch, are still not free.

    additional note: there is overhead in the async processing, so if the action has no async calls or tasks, it should not be declared async.

    0 comments No comments

  2. Lex Li (Microsoft) 4,742 Reputation points Microsoft Employee
    2021-11-14T23:38:23.823+00:00

    ASP.NET 1.0 to 3.5 only has a sync model for request processing, so it suffers bad performance in certain scenarios (such as under burst load).

    More than a decade ago, ASP.NET 4.0 introduced the async model so that performance can be significantly improved, and that model has been passed on to all later releases (4.5 to 4.8) as well as ASP.NET Core.

    More technical details on the async model can be found in articles like this.

    There are almost no disadvantages to use the async model due to the obvious advantages you get and that's why today developers prefer the async model. Sadly the sync model was not removed, so you still has to ask such a question.

    0 comments No comments