Search code examples
c#asp.netasp.net-mvc-4asynchronousasync-await

When should I use async controllers in ASP.NET MVC?


I have some concerns using async actions in ASP.NET MVC. When does it improve performance of my apps, and when does it not?

  1. Is it good to use async action everywhere in ASP.NET MVC?
  2. Regarding awaitable methods: shall I use async/await keywords when I want to query a database (via EF/NHibernate/other ORM)?
  3. How many times can I use await keywords to query the database asynchronously in one single action method?

Solution

  • Asynchronous action methods are useful when an action must perform several independent long running operations.

    A typical use for the AsyncController class is long-running Web service calls.

    Should my database calls be asynchronous ?

    The IIS thread pool can often handle many more simultaneous blocking requests than a database server. If the database is the bottleneck, asynchronous calls will not speed up the database response. Without a throttling mechanism, efficiently dispatching more work to an overwhelmed database server by using asynchronous calls merely shifts more of the burden to the database. If your DB is the bottleneck, asynchronous calls won’t be the magic bullet.

    You should have a look at 1 and 2 references

    Derived from @PanagiotisKanavos comments:

    Moreover, async doesn't mean parallel. Asynchronous execution frees a valuable threadpool thread from blocking for an external resource, for no complexity or performance cost. This means the same IIS machine can handle more concurrent requests, not that it will run faster.

    You should also consider that blocking calls start with a CPU-intensive spinwait. During stress times, blocking calls will result in escalating delays and app pool recycling. Asynchronous calls simply avoid this