在任务中等待异步/等待

Nat*_*per 46 .net c# task task-parallel-library async-await

我有这个构造main(),它创造了

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
Run Code Online (Sandbox Code Playgroud)

但是,当我.Wait为t时,它不会等待呼叫DoBar()完成.我怎么让它实际等待?

i3a*_*non 94

它鼓励使用Task.Factory.StartNewasync-await,你应该使用Task.Run来代替:

var t = Task.Run(
    async () =>
    {
        Foo.Fim();
        await Foo.DoBar();
    });
Run Code Online (Sandbox Code Playgroud)

Task.Factory.StartNewAPI是在之前建造的基于任务的异步模式(TAP)async-await.它将返回,Task<Task>因为您正在使用lambda表达式启动任务,该表达式恰好是异步的,因此返回任务.Unwrap将提取内部任务,但Task.Run会隐含地为您执行此操作.


为了进行更深入的比较,总有一篇相关的Stephen Toub文章:Task.Run vs Task.Factory.StartNew

  • 正要询问如何使用新工厂传递 LongRunning 参数,然后发现您写的这篇优秀博客文章:http://blog.i3arnon.com/2015/07/02/task-run-long-running/你的回答与那篇文章相结合真的帮助了我! (2认同)

Nat*_*per 6

Unwrap()通过执行任务,我似乎获得了所需的功能。我不太确定我是否知道这背后的原因,但我想它可行。

var t = Task.Factory.StartNew(
            async () =>
                {
                        Foo.Fim();
                        await Foo.DoBar();
                }).Unwrap();
Run Code Online (Sandbox Code Playgroud)

编辑:我一直在寻找ddescription Unwrap()Creates a proxy Task that represents the asynchronous operation of a Task<Task<T>> 我传统上认为这是任务的工作,但是如果我需要调用unwrap,我想那很好。

  • [此答案说明了展开。](http://stackoverflow.com/a/24777502/7724) (2认同)