Deep understanding of async / await on ASP.NET MVC

前端 未结 3 786
忘掉有多难
忘掉有多难 2021-02-01 02:39

I don\'t understand exactly what is going on behind the scenes when I have an async action on an MVC controller especially when dealing with I/O operations. Let\'s say I have an

3条回答
  •  既然无缘
    2021-02-01 02:48

    There's some good resources on the 'net that do describe this in detail. I wrote an MSDN article that describes this at a high level.

    What i do not understand is why the request is still alive and waits for an answer because in the end the calling client will wait for our request to complete.

    It's still alive because the ASP.NET runtime has not yet completed it. Completing the request (by sending the response) is an explicit action; it's not like the request will complete on its own. When ASP.NET sees that the controller action returns a Task/Task, it will not complete the request until that task completes.

    My question is: Who / when / how does this wait for complete blocking occurs ?

    Nothing is waiting.

    Think of it this way: ASP.NET has a collection of current requests that it's processing. For a given request, as soon as it's complete, the response is sent out and then that request is removed from the collection.

    The key is that it's a collection of requests, not threads. Each of those requests may or may not have a thread working on it at any point in time. Synchronous requests always have a single thread (the same thread). Asynchronous requests may have periods when they don't have threads.

    Note: i saw this thread: http://blog.stephencleary.com/2013/11/there-is-no-thread.html and it makes sense for GUI applications but for this server side scenario I don't get it.

    The threadless approach to I/O works exactly the same for ASP.NET apps as it does for GUI apps.

    Eventually, the file write will complete, which (eventually) completes the task returned from ReadFile. This "completing of the task" work is normally done with a thread pool thread. Since the task is now complete, the Upload action will continue executing, causing that thread to enter the request context (that is, there is now a thread executing that request again). When the Upload method is complete, then the task returned from Upload is complete, and ASP.NET writes out the response and removes the request from its collection.

提交回复
热议问题