Reputation: 1772
Why second thead started by line
var finalTask = parent.ContinueWith( .. )
is not waiting for first thread's end? This is printout proving that the new thread is not waiting for the first one's end:
Starting main thread 1
Starting ContinueWith thread 2
0 0 0
Ending ContinueWith thread 2
ContinueWith thread is finished!
Starting child thread 3
Ends child thread 3
Starting child thread 2
Ends child thread 2
Starting child thread 1
Ends child thread 1
Code:
public static void AttachTasksToMain()
{
Task<Int32[]> parent = Task.Run(() =>
{
Console.WriteLine("Starting main thread 1");
var results = new Int32[3];
new Task(() => {
Console.WriteLine("Starting child thread 1");
results[0] = 0;
Console.WriteLine("Ends child thread 1");
}, TaskCreationOptions.AttachedToParent).Start();
new Task(() => {
Console.WriteLine("Starting child thread 2");
results[1] = 1;
Console.WriteLine("Ends child thread 2");
}, TaskCreationOptions.AttachedToParent).Start();
new Task(() => {
Console.WriteLine("Starting child thread 3");
results[2] = 2;
Console.WriteLine("Ends child thread 3");
}, TaskCreationOptions.AttachedToParent).Start();
//this thread finishes when all child-thread are finished!
return results;
});
//parent.Wait();
var finalTask = parent.ContinueWith(parentTask =>
{
Console.WriteLine("Starting ContinueWith thread 2");
foreach (int i in parentTask.Result)
Console.WriteLine(i);
Console.WriteLine("Ending ContinueWith thread 2");
});
finalTask.Wait();
Console.WriteLine("ContinueWith thread is finished!");
}
Upvotes: 2
Views: 171
Reputation: 7354
The problem is Task.Run
. This starts the task with TaskCreationOptions.DenyChildAttach
.
A simple change to using Task.Factory.StartNew
and the problem is solved. That's because the default here is TaskCreationOptions.None
.
See here for an in depth discussion of the difference.
Upvotes: 4