Parallel.ForEach中的不一致性

本文关键字:不一致性 ForEach Parallel | 更新日期: 2023-09-27 18:06:16

我使用Parallel。

我的循环是这样的:

Parallel.ForEach(indexes, (index) =>
 {
 //parentCreation with index object
 parent=create(index);
//call of function to create children
createChildrenOfType1(parent);
createChildrenOfType2(parent);
 });

我面临不一致的输出。父级创建正确,但子级创建不一致。有时不创建子进程,有时只创建几个子进程,等等。子创建方法也有for循环来创建100个子。

如何使我的子创建一致,而使用并行foreach父创建

Parallel.ForEach中的不一致性

我在这里看到的一个问题是,您正在修改未在并行中声明的变量。对于每个代码块,在这种情况下,您应该锁定它们。

Parallel.ForEach(indexes, (index) =>
 {
 //parentCreation with index object
lock (lockerObject)
{
     parent=create(index);
    //call of function to create children
    createChildrenOfType1(parent);
    createChildrenOfType2(parent);
}
 });

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

另外,如果你有一个Parent的外部集合,你正在添加新实例化的父类,这也必须是线程安全的,否则你可能会失去你的父类实例。