异步等待和线程

Async await and threads

我正在处理 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.

但是在ThreadPoolclass(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 任务是否使用单独的线程。请解释一下。谢谢。

async/await 在 Tasks 上工作(不完全是,它在 "awaitables" 上工作,但只是说 "Task" 就足够接近这个讨论了)。

任务代表 "A unit of work that will be completed at a later time"。该工作单元可以是通过 Task.Run( 启动的线程池中的新线程,也可以是像 DbDataReader.ReadAsync(), or it could be triggered by a event from a TaskCompletionSource.

这样的系统 IO 调用

我建议阅读 Stephen Cleary 的 async and await intro 以了解有关

的更多信息

用简单的术语来说,Task 可以 运行 在不同的 Thread 上,也可以 运行 在调用方 Thread 上。当调用者 Thread 没有 运行 另一个 Task 的资源时,任务将从 ThreadPool 获取 Thread . Task 将在调用者 Thread 上 运行 当它有足够的资源来 运行 另一个 Task (空闲模式)时。

Compared to a thread, a Task is a higher-level abstraction—it represents a concurrent operation that may or may not be backed by a thread. Tasks are compositional (you can chain them together through the use of continuations). They can use the thread pool to lessen startup latency, and with a TaskCompletionSource, they can leverage a callback approach that avoid threads altogether while waiting on I/O-bound operations.

资料来源:第 565 页 "C# 5.0 in a Nutshell",作者 Joseph Albahari、Ben Albahari。

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

如果您 await 一个 Task,您 return 控制流到您的方法的调用者,直到 "someone" 将 Task 设置为完成。

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