等待异步/等待一个任务里 [英] 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
为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
与异步计谋
,你应该使用 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)和异步等待
。它会返回任务&LT;任务&GT;
,因为你开始一个lambda EX pression这恰好是异步,因此返回一个任务一个任务。 展开
将提取的内部任务,但 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.
有关更深入的比较,总有一个相关的斯蒂芬Toub的文章:任务。运行VS Task.Factory.StartNew
For a deeper comparison, there's always a relevant Stephen Toub article: Task.Run vs Task.Factory.StartNew
这篇关于等待异步/等待一个任务里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!