c# - 上次。等待与线程一起工作吗?

标签 c# asynchronous synchronization task async-await

之前看到一些类似的问题,想弄清楚。

this article ,据说异步调用“没有线程”

然而,in another one ,据说

Here, however, we’re running the callback to update the Text of textBox1on some arbitrary thread, wherever the Task Parallel Library (TPL) implementation of ContinueWith happened to put it.

另外,在某些情况下,当我在我的项目中调用 ContinueWith 时,我也会遇到“跨线程访问异常”。

那么,谁是对的?

答案:感谢 i3arnon。仔细阅读第一篇文章后,我找到了这个地方

So, we see that there was no thread while the request was in flight. When the request completed, various threads were “borrowed” or had work briefly queued to them. This work is usually on the order of a millisecond or so (e.g., the APC running on the thread pool) down to a microsecond or so (e.g., the ISR). But there is no thread that was blocked, just waiting for that request to complete.

最佳答案

两者都是。当您的 CPU 上运行代码时,总会有一个线程在运行它。问题是当您没有要运行的代码时会发生什么,例如当您等待 IO 操作完成时。

如果您在应该使用async await 的地方使用,则不会有线程空闲地等待该操作完成,只有它完成后才会给出一个线程(通常由 线程池) 继续在您的 CPU 上运行代码。

当您不使用 async-await(或不同的异步范例,如 Begin-End)时,您将贯穿保持一个线程操作,即使是在它的 IO 部分,也是一种资源浪费。


重要的是要补充一点,尽管大多数异步示例都涉及 IO 操作,但情况并非总是如此。在某些情况下,异步处理 CPU 密集型操作(在整个操作过程中您确实持有一个线程)是合理的。

关于c# - 上次。等待与线程一起工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23870771/

相关文章:

c# - 尝试单击按钮登录网站

mysql - Wordpress 后期同步/发布到生产环境

java - 将字符串转换为数组再转换为 Observable 中的对象

javascript - Android 开发 - 在正常代码运行之前获取异步任务的结果

c# - 在前提完成之前继续运行

c++ - if block 的同步,C++

c++ - 共享内存 IPC 同步(无锁)

c# - 调用 Async WebAPI 后,控制不会返回到等待的 webClient

c# - 多行问题 WPF TextBox

c# - 可以从不同对象集返回的谓词或动态 Linq?