c# - 异步等待和线程

标签 c# .net multithreading async-await threadpool

<分区>

我正在使用 async-await 和任务,但我无法理解一件事:

异步任务是否在单独的线程中执行?

正如 msdn 所说 ( Asynchronous programming ):

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread.

但是在 ThreadPool 类(ThreadPool Class)描述的备注中:

Examples of operations that use thread pool threads include the following:

When you create a Task or Task object to perform some task asynchronously, by default the task is scheduled to run on a thread pool thread.

所以,现在我不明白 async 任务是否使用单独的线程。请解释一下。谢谢。

最佳答案

Task 不一定代表一个额外的线程。

如果您await一个Task,您会将控制流返回给方法的调用者,直到“某人”将Task设置为已完成.

如果您通过 Task.Run()Task.Factory.StartNew() 启动一个 Task,那么您传递给这些调用是在另一个线程上执行的(不是新线程,而是来自 ThreadPool 的线程)。

关于c# - 异步等待和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37278281/

相关文章:

.net - WinForms : Implementation question for having my UI run independently of my BLL layer?

java - 为这种情况动态生成线程 Java

java - JSP 中的 session 变量

c# - 对于 35 张图像,如何在获取 1 个特定像素的颜色时获得最佳性能?

c# - 如何更新照片上的时间戳或在 Google+ 照片上添加时区?

c# - 在 C# 中编写 C++ std::reverse 等效项的最接近方法是什么?

c# - 如何在 C# 中使用 iTextSharp 将添加的图像带到最前沿

c# - 如何将旧的 WinForms 项目迁移到新的 VS2017 项目格式

c# - ASP.NET:通过UserControl调用MasterPage中的函数

c# - 使用 StreamReader 生成 ID(最后一行)