父/子任务无法按预期工作 [英] Parent/Child Tasks Not Working As Expected

查看:69
本文介绍了父/子任务无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为C#考试070-483学习.我正在看孩子/父母的工作,很困惑.在我看来,父任务只有在所有子任务完成后才能运行.举个例子:

I am starting to study for the C# exam 070-483.  I am looking at child/parent tasks and am very confused.  It seems to me that the parent task does not complete it's run until all of it's children tasks complete.  Take this example:

Task parent = Task.Run(() => 
            {
                new Task(() => 
                { 
                    Console.WriteLine("Sleeping...");     
                    Thread.Sleep(5000); 
                },  
                TaskCreationOptions.AttachedToParent
                ).Start();
                
                int i = 0;
                for (i = 0; i < 10; i++)
                {
                    //Doing some work in here
                }
                Console.WriteLine("i is {0}", i);
            });

运行此命令时,父任务的底部"Console.WriteLine("i为{0}",i)在假定的刚刚睡着的孩子任务执行之前执行.

When I run this, the bottom of the parent task "Console.WriteLine("i is {0}", i)" executes before the supposed child task of just sleeping executes. 

我一定对父母任务的关系有误解.我的理解使我相信,一旦子任务开始,父任务中的其他任务将不会执行,直到该子任务完成为止.您可以帮忙澄清一下吗?

I must be misunderstanding the parent and child task relationship.  My understanding led me to believe that once the child task started, nothing else in the parent task would execute until that child task was done.  Can you help with some clarification?

推荐答案

来自 任务.运行 方法."因此,您的子任务未附加到父任务.
From this article, (3rd paragraph from "Attached Child Task" section)" Parent tasks implicitly prevent child tasks from attaching to them if they are created by calling the Task.Run method." therefore your child task is not attached to parent.


这篇关于父/子任务无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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