异步/等待 vs 线程

在.Net 4.5中,微软增加了新的 Async/Await特性来简化异步编码

  1. Async/Await可以完全取代旧的使用方式 Threads?
  2. Async/Await能做任何 Thread能做的事情吗 不同步?
  3. 可以 Async/Await只用于一些方法,如 WebClient.DownloadStringAsync或我可以转换任何同步方法,使它使用 Async/Await,而不是阻塞主线程?
69692 次浏览

它能完全取代旧的使用线程的方式吗?

没有。线程可以做许多更有用的事情。Await 是专门为处理 something占用时间而设计的,最典型的是 I/O 请求。传统上在 I/O 请求完成时通过回调完成。编写依赖于这些回调的代码是相当困难的,有待大大简化。

能够完成任何一个线程可以异步完成的任务?

Roughly. Await just takes care of dealing with the delay, it doesn't otherwise do anything that a thread does. The await 表情, what's at the right of the await keyword, is what gets the job done. Ideally it doesn't use a thread at all, it posts a driver request and once the driver completes the data transfer it generates a completion notification callback. Networking is by far the most common usage, latencies of hundreds of milliseconds are common and an inevitable side-effect of services moving from the desktop or a LAN into "the cloud". Using such services synchronously would make a UI quite unresponsive.

只能与 WebClient.DownloadStringAsync 等方法一起使用

No. You can use it with any method that returns a Task. The XxxxAsync() methods are just precooked ones in the .NET framework for common operations that take time. Like downloading data from a web server.

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

Async/wait 是在主应用程序线程上运行一些代码的快速方法,其优点是,当代码没有工作要做时,它可以暂停自己,然后将焦点返回到主线程,当有结果要获得时,在主线程上“唤醒”,然后将处理返回给——你猜对了——主线程。可以把它想象成 Basic 中基于事件的 GOTO 语句,它可以将控制来回传递给特定的执行行。

相比之下,线程是一个独立的执行流,它可以用自己的变量等运行,在有足够硬件的情况下,执行发生在与主线程并行的情况下。

如果您有一个 GUI 应用程序,它将下载一个文件,然后在下载该文件时对其进行处理,那么我将使用异步/等待方法来实现它。

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.