How and when to use ‘async’ and ‘await’

前端 未结 21 2227
你的背包
你的背包 2020-11-21 05:07

From my understanding one of the main things that async and await do is to make code easy to write and read - but is using them equal to spawning background threads to perfo

21条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-21 05:17

    Tasks let you control the number of threads you are running on.
    The optimal number of threads is the number of cores you have.

    • when your app is Console, WinForms or WPF then you are normally running on a single-thread.

      • in this case you want to increase the number of threads
      • your main tool is Task.Run(), and sometimes Parallel.ForERach()
      • doing synchronous I/O on a thread (with Task.Run()) is sub-optimal but acceptable
    • when your app runs on a Webserver it normally is running on (too) many threads.
      asp.net waits for incoming requests and quickly hands each one to a new pool thread.

      • in this case you want to decrease the number of threads
      • your main tool is to await asynchrous I/O
      • make sure you have an unbroken await chain from your async Action method down to the actual I/O
      • doing synchronous I/O or CPU intensive work on a thread (with Task.Run()) is a de-optimization.

提交回复
热议问题