Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
945 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...