C# Task – Attached and Detached Child Tasks

Developers can define parent-child relationships between task. The main idea is, parent task is completed when all its children tasks are completed.

Example1:

private static void childrenTasksExample()
{
    var parent = Task.Factory.StartNew(() =>
    {
      Console.WriteLine("Parent task executing.");
      var child1 = Task.Factory.StartNew(() =>
    {

    Console.WriteLine("Attached child starting.");
    Console.WriteLine("Attached child completing.");
 }, TaskCreationOptions.AttachedToParent);
});
parent.Wait();
Console.WriteLine("Parent has completed.");
}

Output1:

Please notice to parent.Wait() method. Its says to the parent that it will be completed when everything inside it is completed.
If you will try to run without mentioned earlier string, the results will be “slightly” different.

Output:

Now we would like to execute 2 sons tasks within father task. We can achieve it like following (as expected)

Example2:

private static void childrenTasksExample()
{
var parent = Task.Factory.StartNew(() =>
{
Console.WriteLine("Parent task executing.");
var child1 = Task.Factory.StartNew(() =>
{
Console.WriteLine("Attached child1 starting.");
Console.WriteLine("Attached child1 completing.");
}, TaskCreationOptions.AttachedToParent);

var child2 = Task.Factory.StartNew(() =>
{
Console.WriteLine("Attached child2 starting.");
Console.WriteLine("Attached child2 completing.");
}, TaskCreationOptions.AttachedToParent);

});
parent.Wait();
Console.WriteLine("Parent has completed.");
}

Output2:

 

Notice that code is not define who run first within father’s task. It only says that father task will complete only after everything else is completed inside it.

To explore:

Let say that we second son should be executed right after first one is completed.  So how do we achieve it ? MSDN suggest us to use TaskCreationOptions.PreferFairness. I will cover it in my future posts.

Related sources (links):

Leave a Reply

Your email address will not be published. Required fields are marked *