Samy Boulos
Samy Boulos

Reputation: 113

Child Tasks Vs WaitAll

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();
}

Upvotes: 4

Views: 195

Answers (1)

svick
svick

Reputation: 244767

AttachedToParent offers you a different way to structure your code. If child Tasks can start in various places in the code of the parent Task, using AttachedToParent means you don't have to worry about collecting all the child Tasks into a collection.

In practice, I think that Task.WaitAll() is clearer and collecting the Task is not actually a problem, so I would almost never use AttachedToParent.

Upvotes: 5

Related Questions