Task.ContinueWith()父任务不等待子任务完成 [英] Task.ContinueWith() parent task doesn't wait for child task to finish

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

问题描述

自从我理解工作的嵌套任务的情况下,我真不明白,但─为什么之前第​​二打印第三打印?

Since I was understanding the Task in context of nested task, I really don't understand that- Why the 3rd print before 2nd print?

虽然,我已经使用 Task.WaitAll(T),它打印的 3 的行之前的第二的行

Even though, I have used Task.WaitAll(t), it print 3rd line before 2nd line.

code:

public static void Main()
        {

            Task t = new Task(
                () =>
                {
                    Thread.Sleep(2000);
                    Console.WriteLine("1st print...");
                });
           t.ContinueWith(
                x =>
                {
                    Thread.Sleep(2000);
                    Console.WriteLine("2nd print...");
                },
                TaskContinuationOptions.OnlyOnRanToCompletion);

            t.Start();
            Task.WaitAll(t);

            Console.WriteLine("3rd print...");
            Console.Read();

}

输出:

推荐答案

您需要等待的延续也:

Task t2 = t.ContinueWith( /* .. */ );
Task.WaitAll(new [] { t, t2 } );

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

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