Async and Await in ApiController Post

前端 未结 2 1091
孤独总比滥情好
孤独总比滥情好 2021-02-05 14:07

I\'m still not quite clear about async and await in .net 4.5. So far, I think I understand that await:

  1. puts the function (to its right) on a separate thread.
相关标签:
2条回答
  • 2021-02-05 14:33

    In addition to Stephen's answer I need to point out a few things.

    First, async in the controller does not make the user experience async. User will have to wait as long as SomeReallyLongRunningTaskAsync() takes. [So why do we do async? See the next point]

    Also, if the SomeReallyLongRunningTaskAsync() is CPU-bound, then you should not call it in async mode. The main reason to use Async in a server scenario is to release the CLR thread back to the pool so that the IO Completion Port (IOCP) can handle the rest - until IO work done which then goes back to the thread pool. This will prevent the problem of Thread Starvation which is common in ASP.NET Scenarios.

    IOCPs are used ONLY in IO-bound situations, examples are:

    • reading from/writing to a file
    • accessing database or
    • accessing an external Web Service or WCF service

    There are tons of resources available online and explain various aspects. If I may put a plug, Chapter 2 of this book is an excellent resource which gives a cohesive understanding of Async in Web API.

    0 讨论(0)
  • 2021-02-05 14:35

    puts the function (to its right) on a separate thread.

    No. async does not start a new thread. I have an async intro that you may find helpful.

    Post will finish execution and return control to whoever called myApiController.Post(obj). But I don't have the HttpResponseMessage object yet

    Correct.

    In this above simple example, would the call immediately return to the client (that is, client JS website or mobile app)?

    No. ASP.NET MVC 4.5 sees that you're returning Task<HttpResponseMessage> and not HttpResponseMessage, so it will not send the response until your Task is completed (at the end of your async Post method).

    0 讨论(0)
提交回复
热议问题