TPL: Parent-Child Tasks and Captured Variables
What do you think will be the return value of the Task named “parentTask”?
If a parent-child task hierarchy is set by using TaskCreationOptions.AttachedToParent when creating child tasks, then the parent task waits for all the child tasks to finish. But just because the parent waits for its children to finish, it doesn’t mean it would wait for them before determining its return value.
In the sample above, the line parentTask.Result is a blocking call and so it would wait for the parentTask to finish. But still the increments in the child tasks do not affect the captured variable “i”. The parentTask would need to explicitly wait for the child tasks to return the correct value.
The output of above sample is: