Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a Nested Task and Child Task

i like to understand what is the difference between Nested Task and Child Task.

var outerTask = Task.Factory.StartNew( () => 
{
    var nestedTask = Task.Factory.StartNew( () => 
    {
         Console.WriteLine("Inside nestedTask");
    });
});


A "child task" looks like this:

var parentTask = Task.Factory.StartNew( () => 
{
    var childTask = Task.Factory.StartNew( () => 
    {
         Console.WriteLine("Inside childTask");
    },               TaskCreationOptions.AttachedToParent );
});

here i have attach the code.

it seems that when we start any nested task then outer task may complete before inner task but in case of child task always child task complete before parent task. i am not sure that am i right or not. so it will be helpful if anyone guide me when to go for nested task and when child task with sample scenario. thanks

like image 957
Thomas Avatar asked Nov 18 '13 13:11

Thomas


2 Answers

IMO, the best explanation is found in Stephen Toub's blog post:

... the Task being created registers with that parent Task as a child, leading to two additional behaviors: the parent Task won’t transition to a completed state until all of its children have completed as well, and any exceptions from faulted children will propagate up to the parent Task (unless the parent Task observes those exceptions before it completes).

like image 128
noseratio Avatar answered Sep 21 '22 09:09

noseratio


Microsoft explain this one handsomely.

A nested task is just a Task instance that is created in the user delegate of another task. A child task is a nested task that is created with the AttachedToParent option. A task may create any number of child and/or nested tasks, limited only by system resources. The following example shows a parent task that creates one simple nested task.

...

The most important point with respect to child vs. nested tasks is that nested tasks are essentially independent from the parent or outer task, whereas attached child tasks are very closely synchronized with the parent.

http://msdn.microsoft.com/en-us/library/vstudio/dd997417%28v=vs.100%29.aspx

like image 25
Gusdor Avatar answered Sep 18 '22 09:09

Gusdor