Why use async controllers, when IIS already handles the request concurrency?

后端 未结 3 1654
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-11 14:12

I wonder why I should bother using async Task on controllers, when IIS already handles the concurrency for me?

http://msdn.microsoft.com/en-us/library/dd560842.aspx

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-11 14:57

    As others have pointed out, async allows the request thread to return to the thread pool while it's doing an asynchronous operation. With synchronous handlers, your server will end up with threads blocked on I/O, essentially doing nothing important but also not able to be used for other requests while they're blocked. async just frees up those threads so that they are useful all the time.

    So, the first thing of note is that the question "async or the thread pool" is the wrong question. When you use async, you're allowing ASP.NET to make maximum use of the existing thread pool. async takes the existing (parallel) concurrency in ASP.NET and adds (asynchronous) concurrency to achieve greater scalability.

    But the question remains of "why"? The reasons are twofold: async can scale further than (just) the thread pool, and async is also more responsive. As mentioned in the comments on the other answers, threads are pretty heavyweight objects to be wasting unnecessarily; the memory for asynchronous operations is much less than that used by a thread. The second reason is also important: when a sudden burst of requests come in, the thread pool (by itself) can only expand at a limited rate; async enables the thread pool to handle bursts of requests much more efficiently.

提交回复
热议问题