Deep understanding of async / await on ASP.NET MVC

前端 未结 3 790
忘掉有多难
忘掉有多难 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:53

    The ASP.NET runtime understands what tasks are and delays sending the HTTP response until the task is done. In fact the Task.Result value is needed in order to even generate a response.

    The runtime basically does this:

    var t = Upload(...);
    t.ContinueWith(_ => SendResponse(t));
    

    So when your await is hit both your code and the runtimes code gets off the stack and "there is no thread" at that point. The ContinueWith callback revives the request and sends the response.

提交回复
热议问题