等待任务中的Task.WhenAll()未等待 [英] Await Task.WhenAll() inside task not awaiting

查看:182
本文介绍了等待任务中的Task.WhenAll()未等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,当一个任务有一个Task.WhenAll()调用(运行其他任务)时,WhenAll()这一行使消耗代码继续执行,这与我的预期不同.因此,下面的代码在命中Task.WhenAll()时立即输出"finished"(完成),而不是在其参数中的所有任务都完成之后.

My problem is that when a Task has a Task.WhenAll() call (running other Tasks) the line of WhenAll() makes the consuming code continue execution, unlike what I would expect. So the following code outputs "finished" immediately when the Task.WhenAll() is hit, not after all the tasks in its argument are finished.

    // Just a simple async method
    public Task DoWorkAsync()
    {
        return Task.Factory.StartNew(
            () =>
            {
                // Working
            });
    }

    // This one used the previous one with Task.WhenAll()
    public Task DoLoadsOfWorkAsync()
    {
        return Task.Factory.StartNew(
            async () =>
            {
                // Working
                // This line makes the task return immediately
                await Task.WhenAll(DoWorkAsync(), DoWorkAsync());
                // Working
            });
    }

    // Consuming code
    await DoLoadsOfWorkAsync();
    Console.WriteLine("finished");

我希望在执行DoLoadsOfWorkAsync()的最后一行时调用WriteLine().

I'd expect the WriteLine() to be called when the last line of DoLoadsOfWorkAsync() is executed.

我做错了什么?预先感谢.

What am I doing wrong? Thanks in advance.

推荐答案

Task.WhenAll 返回一个新的

Task.WhenAll returns a new Task immediately, it does not block. The returned task will complete when all tasks passed to WhenAll have completed.

它与 ,这是您要阻止的方法.

It is an asynchronous equivalent to Task.WaitAll, and this is the method to use if you want to block.

但是您还有另一个问题.使用 Task.Factory.StartNew 并传递一个async委托似乎导致了Task<Task>类型,其中内部任务开始执行时(而不是完成时),外部任务完成.

However you have another problem. Using Task.Factory.StartNew and passing an async delegate seems to lead to a type of Task<Task> where the outer task completes when the inner task starts to execute (rather than when it has completed).

使用更新的 Task.Run 避免这种情况.

Using the newer Task.Run avoids this.

这篇关于等待任务中的Task.WhenAll()未等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆