I am not sure what is the benefit of creating child tasks when I can have the parent task wait for all the tasks it created. I run the following code and it produced the same result in both cases.
public static void Main(string[] args)
{
RunWithChildren();
RunWithWait();
}
private static void RunWithChildren()
{
Task<Int32[]> parent = Task.Run(() =>
{
var results = new Int32[3];
new Task(r => results[0] = 0, TaskContinuationOptions.AttachedToParent).Start();
new Task(r => results[1] = 1, TaskContinuationOptions.AttachedToParent).Start();
new Task(r => results[2] = 2, TaskContinuationOptions.AttachedToParent).Start();
return results;
});
var finalTask = parent.ContinueWith(parentTask =>
{
foreach (int i in parentTask.Result)
Console.WriteLine(i);
});
finalTask.Wait();
}
private static void RunWithWait()
{
Task<Int32[]> parent = Task.Run(() =>
{
var results = new Int32[3];
Task t1 = Task.Run(() => results[0] = 0);
Task t2 = Task.Run(() => results[1] = 1);
Task t3 = Task.Run(() => results[2] = 2);
Task.WaitAll(t1, t2, t3);
return results;
});
var finalTask = parent.ContinueWith(parentTask =>
{
foreach (int i in parentTask.Result)
Console.WriteLine(i);
});
finalTask.Wait();
}