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
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With