Ich bin mir nicht sicher, welchen Vorteil das Erstellen untergeordneter Aufgaben hat, wenn die übergeordnete Aufgabe auf alle von ihr erstellten Aufgaben warten kann. Ich führe den folgenden Code aus und es ergab das gleiche Ergebnis in beiden Fällen.Untergeordnete Aufgaben Vs WaitAll
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();
}