Parallel.ForEach

时间:2016-09-08 13:00:52

标签: c# multithreading foreach parallel-processing task-parallel-library

我使用Parallel.foreach进行了500多次迭代。

我的循环类似于:

Parallel.ForEach(indexes, (index) =>
 {

 //parentCreation with index object
 parent=create(index);

//call of function to create children
createChildrenOfType1(parent);
createChildrenOfType2(parent);
 });

我面临着不一致的输出。父母是正确创建的,但是孩子的创造是不一致的。 有时候没有创建子项,有时只创建少量项目等等。 子项创建方法再次具有for循环来创建100个子项。

如何在使用并行foreach进行父级创建时使子项创建保持一致。

2 个答案:

答案 0 :(得分:1)

假设您的Parent对象有一个List<Child> Children并且您的createChildrenOfTypeX函数正在向Parent.Children列表中添加一个新子项,那些createChildrenOfTypeX也在运行一个并行然后List实现必须是线程安全的代码集;标准的System.Collections.Generic实现不是线程安全的。

此外,如果您要将新实例化的父项添加到Parent的外部集合,则还必须是线程安全的,否则您也可能会丢失父实例。

答案 1 :(得分:1)

我在这里看到的一个问题是你正在修改未在Parallel.ForEach代码块中声明的变量,在这种情况下你应该锁定它们。

Parallel.ForEach(indexes, (index) =>
 {

 //parentCreation with index object
lock (parent)
{
     parent=create(index);
}


lock (childrenDefinedElseWhere)
{
    //call of function to create children
    createChildrenOfType1(parent);
    createChildrenOfType2(parent);
}
 });

通过使用lock,它可以确保线程正确同步。