Async and Await in ApiController Post

前端 未结 2 1094
孤独总比滥情好
孤独总比滥情好 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条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题