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

前端 未结 21 1740
你的背包
你的背包 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:22

    From my understanding one of the main things that async and await do is to make code easy to write and read.

    They're to make asynchronous code easy to write and read, yes.

    Is it the same thing as spawning background threads to perform long duration logic?

    Not at all.

    // I don't understand why this method must be marked as 'async'.

    The async keyword enables the await keyword. So any method using await must be marked async.

    // This line is reached after the 5 seconds sleep from DoSomethingAsync() method. Shouldn't it be reached immediately?

    No, because async methods are not run on another thread by default.

    // Is this executed on a background thread?

    No.


    You may find my async/await intro helpful. The official MSDN docs are also unusually good (particularly the TAP section), and the async team put out an excellent FAQ.

提交回复
热议问题