Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Task.WaitAll doesn't wait for child task?

Hello I have _noOfThreads as defined tasks to run at a time. So I keep continuing the Tasks by using % operator and at the end of the loop I have Tasks.WaitAll. This is the code snippet.

for (int index = 0; index < count; index++)
{

                if (index < _noOfThreads)
                    tasks[index] = Task.Factory.StartNew(somedelegate);
                else
                    tasks[index % _noOfThreads].ContinueWith(task => { foo.bar(); }, 
                            TaskContinuationOptions.AttachedToParent);
 }
  Task.WaitAll(tasks);

However, I notice it doesn't wait for child tasks to complete. As soon as the parent tasks complete, the next line after Task.WaitAll gets executed. How do I change this code to wait for child tasks also?

like image 407
Tim Tom Avatar asked May 23 '12 13:05

Tim Tom


2 Answers

I think you are allocating your Tasks as:

Tasks[] tasks = new Task[ _noOfThreads];

Change your code to be:

Tasks[] tasks = new Task[count];

for (int index = 0; index < count; index++)
{

    if (index < _noOfThreads)
         tasks[index] = Task.Factory.StartNew(somedelegate);
    else
         tasks[index] = tasks[index % _noOfThreads].ContinueWith(task => { foo.bar(); }, 
                            TaskContinuationOptions.AttachedToParent);
}
Task.WaitAll(tasks);

Give it a try! Good Luck :)

like image 159
TCM Avatar answered Nov 10 '22 07:11

TCM


You are waiting only for the original task. To wait for all the continuations to complete, you need to call WaitAll on the continuation tasks. Simple way to accomplish this would be to reassign each continuation task back to the original variable so you are waiting only on the final continuations:

else
    tasks[index % _noOfThreads] =
        tasks[index % _noOfThreads].ContinueWith(task => { foo.bar(); }, 
                        TaskContinuationOptions.AttachedToParent);

See also this related question.

like image 3
mellamokb Avatar answered Nov 10 '22 09:11

mellamokb