Async/Await vs Threads

后端 未结 3 1707
天命终不由人
天命终不由人 2020-11-28 02:56

In .Net 4.5 Microsoft has added the new Async/Await feature to simplify asynchronous coding. However, I wonder

  1. Can Async/Await compl
3条回答
  •  一生所求
    2020-11-28 03:15

    I think about it this way (and I think Microsoft does too if you look at https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2012/hh191443(v=vs.110)#threads)

    Async/await is a quick way to run some code on the main application thread with the advantage that the code can suspend itself when it has no work to do and return focus to the main thread, "wake up" on the main thread when there is a result to be obtained and then pass processing back to - you guessed it - the main thread. Think of it like an event based GOTO statement in Basic that can pass control back and forth to a specific line of execution.

    In contrast a thread is a separate stream of execution that can run with its own variables etc. where - given sufficient hardware - execution occurs in parallel to the main thread.

    If you have a GUI application that is going to download a single file and then do something with that file when its downloaded - I'd implement that using an async/await method.

    However if your GUI needs to download 5000 files - I'd create a file download thread to handle that since the main GUI thread may freeze while execution is transferred to handle downloading the files.

提交回复
热议问题