问题描述
在 .Net 4.5 中,Microsoft 添加了新的 Async/Await
功能以简化异步编码.不过,我不知道
In .Net 4.5 Microsoft has added the new Async/Await
feature to simplify asynchronous coding. However, I wonder
- 能否
Async/Await
完全替代旧的使用方式线程
? Async/Await
是否能够做任何Thread
可以做的事情异步?Async/Await
是否可以仅用于某些方法,例如WebClient.DownloadStringAsync
或者我可以转换任何同步方法以使其使用Async/Await代码>而不是阻塞主线程?
- Can
Async/Await
completely replace the old way of usingThreads
? - Is
Async/Await
capable of doing whatever aThread
can doasynchronously? - Can
Async/Await
only be used with some methods likeWebClient.DownloadStringAsync
or can I convert any synchronous method to make it useAsync/Await
and not to block the main thread?
推荐答案
没有.一个线程可以做更多有用的事情.Await 专门用于处理某事 花费时间,最典型的是 I/O 请求.传统上,当 I/O 请求完成时,这是通过回调完成的.编写依赖这些回调的代码相当困难,await 大大简化了它.
No. A thread can do many more useful things. Await is specifically designed to deal with something taking time, most typically an I/O request. Which traditionally was done with a callback when the I/O request was complete. Writing code that relies on these callbacks is quite difficult, await greatly simplifies it.
能够做任何一个线程可以异步做的事情?
大致上.Await 只负责处理延迟,否则它不会执行线程所做的任何事情.await 表达式,位于 await 关键字右侧的内容,用于完成工作.理想情况下,它根本不使用线程,它会发布一个驱动程序请求,一旦驱动程序完成数据传输,它就会生成一个完成通知回调.网络是迄今为止最常见的用法,数百毫秒的延迟很常见,并且是服务从桌面或 LAN 转移到云"的不可避免的副作用.同步使用此类服务会使 UI 完全没有响应.
Roughly. Await just takes care of dealing with the delay, it doesn't otherwise do anything that a thread does. The await expression, 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
没有.您可以将它与任何返回任务的方法一起使用.XxxxAsync() 方法只是 .NET 框架中针对需要时间的常见操作的预制方法.就像从网络服务器下载数据一样.
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.
这篇关于异步/等待与线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!