在任务中等待 async/await [英] Waiting for async/await inside a task
问题描述
我的 main()
中有这个构造,它创建了
I have this construct in my main()
, which creates
var tasks = new List<Task>();
var t = Task.Factory.StartNew(
async () =>
{
Foo.Fim();
await Foo.DoBar();
});
//DoBar not completed
t.Wait();
//Foo.Fim() done, Foo.DoBar should be but isn't
然而,当我 .Wait
for t 时,它不会等待对 DoBar()
的调用完成.我如何让它真正等待?
However, when I .Wait
for t, it won't wait for the call to DoBar()
to complete.
How do I get it to actually wait?
推荐答案
不鼓励使用 Task.Factory.StartNew
和 async-await
,你应该使用 Task.Run
代替:
It's discouraged to use Task.Factory.StartNew
with async-await
, you should be using Task.Run
instead:
var t = Task.Run(
async () =>
{
Foo.Fim();
await Foo.DoBar();
});
Task.Factory.StartNew
api 是在 基于任务的异步模式 (TAP) 和 async-await
.它将返回 Task
因为您正在使用 lambda 表达式启动一个任务,该表达式恰好是异步的,因此返回一个任务.Unwrap
将提取内部任务,但 Task.Run
会隐式地为您完成.
The Task.Factory.StartNew
api was built before the Task-based Asynchronous Pattern (TAP) and async-await
. It will return Task<Task>
because you are starting a task with a lambda expression which happens to be async and so returns a task. Unwrap
will extract the inner task, but Task.Run
will implicitly do that for you.
为了更深入的比较,总有一篇相关的 Stephen Toub 文章:Task.Run vs Task.Factory.StartNew
For a deeper comparison, there's always a relevant Stephen Toub article: Task.Run vs Task.Factory.StartNew
这篇关于在任务中等待 async/await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!