Task.WaitAll not waiting for a child task?

Hello, I have _noOfThreadsboth given tasks to run at the same time. Therefore, I continue to perform tasks with the help of the operator %, and at the end of the cycle I have Tasks.WaitAll. This is a piece of code.

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 noticed that he did not wait for the completion of the child tasks. As soon as the parent tasks complete, the next line after is executed Task.WaitAll. How do I change this code to wait for child tasks?

+5
source share
2 answers

I think you highlight your tasks as:

Tasks[] tasks = new Task[ _noOfThreads];

Change your code:

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 :)

+8
source

. , WaitAll . , :

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

. .

+3

All Articles