问题描述
我正在使用async-await
和任务,但是我无法理解一件事:
I am working with async-await
and tasks, but I can't understand the one thing:
异步任务是否在单独的线程中执行?
如msdn所说(异步编程):
但是在ThreadPool
类的说明中的备注中(线程池类):
But in the remarks in description of ThreadPool
class (ThreadPool Class):
创建任务或任务对象以异步执行某些任务时,默认情况下,该任务计划在线程池线程上运行.
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
任务是否使用单独的线程.请给我解释一下.谢谢.
So, now I don't understand if async
task uses separate thread. Explain me please. Thanks.
推荐答案
Task
不一定 表示多余的线程.
A Task
does not necessarily represent an extra thread.
如果您await
一个Task
,则将控制流返回到方法的调用者,直到某人"将Task
设置为已完成.
If you await
a Task
, you return the control flow to the caller of your method until "someone" sets the Task
as completed.
如果通过Task.Run()
或Task.Factory.StartNew()
启动Task
,则传递给这些调用的操作将在另一个线程上执行(不是新线程,而是ThreadPool中的一个).
If you start a Task
via Task.Run()
or Task.Factory.StartNew()
, then the action you pass to these calls is executed on another thread (not a new one, but one from the ThreadPool).
这篇关于异步等待和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!