Task.WaitAll不等待子任务?

时间:2012-05-23 13:16:42

标签: c# .net multithreading c#-4.0 task-parallel-library

您好我有_noOfThreads作为定义的任务一次运行。所以我继续使用%运算符继续执行任务,在循环结束时我有Tasks.WaitAll。这是代码段。

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

但是,我注意到它不等待子任务完成。父任务完成后,Task.WaitAll执行后的下一行。如何更改此代码以等待子任务?

2 个答案:

答案 0 :(得分:8)

我认为您将任务分配为:

Tasks[] tasks = new Task[ _noOfThreads];

将您的代码更改为:

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

试一试!祝你好运:)

答案 1 :(得分:3)

您只等待原始任务。要等待所有延续完成,您需要在继续任务上调用WaitAll。完成此操作的简单方法是将每个延续任务重新分配给原始变量,这样您只需等待最后的延续:

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

另见this related question

相关问题