任务并行库不适用于内部 foreach 循环
本文关键字:内部 foreach 循环 适用于 不适用 并行 任务 | 更新日期: 2023-09-27 18:33:27
基本上我正在尝试使用task一起运行四个函数。这四个函数运行自己的 ForEach 循环。当我执行这些函数时,不断出现错误。"收藏被修改;枚举操作可能无法执行。'"
到目前为止,我已经尝试过的方法:
方法 1:失败
var tasks = new[]
{
Task.Factory.StartNew(() => function1(publishrequest,nextshiftRq, publishList)),
Task.Factory.StartNew(() => function2(publishrequest,nextshiftRq, publishList)),
Task.Factory.StartNew(() => function3(publishrequest,nextshiftRq, publishList)),
Task.Factory.StartNew(() => function4(publishrequest,nextshiftRq, publishList))
};
Task.WaitAll(tasks);
方法 2:失败
List<Task> tasks = new List<Task>();
tasks.Add(Task.Factory.StartNew(() => function1(publishrequest, nextshiftRq, publishList)));
tasks.Add(Task.Factory.StartNew(() => function2(publishrequest, nextshiftRq, publishList)));
tasks.Add(Task.Factory.StartNew(() => function3(publishrequest, nextshiftRq, publishList)));
tasks.Add(Task.Factory.StartNew(() => function4(publishrequest, nextshiftRq, publishList)));
Task.WaitAll(tasks.ToArray());
方法 3:失败
Parallel.Invoke(
() = {function1(publishrequest, nextshiftRq, publishList)},
() = {function2(publishrequest, nextshiftRq, publishList)},
() = {function3(publishrequest, nextshiftRq, publishList)},
() = {function4(publishrequest, nextshiftRq, publishList)});
在函数中内部
public void function1(publish p1,nextshift nx, List<publish> pub)
{
foreach(publish in pub.ToList())
{
Evaluate.EvaluateShift(p1.publishShift.ShiftRpt,publish.SectionId);
Evaluate.EvaluateShift(nx,publish.SectionId);
}
}
这个函数 1 再次调用另一个函数,其中另一个 foreach 循环正在运行。
//Evaluate.Evaluateshift
Evaluateshift(shiftRpt rpt, int sectionId)
{
ShiftPI currentShiftI = DataService.GetEntity(GetDataRequest<ShiftPI>.Create(c =>
c.ShiftID == rpt.ShiftID && c.SectionPanelID == sectionId, "ShiftPI"));
if(currentShiftI != null)
{
List<SectionPanelPI> sectionPanelPIs = DataService.GetAll(GetDataRequest<SectionPanelHSEKPI>.Create(c =>
c.SectionPanelID == sectionId, "PI", "PIStatistics")).ToList();
foreach(sectionPanelPI in sectionPanelPIs)
{
do more stuff....
}
}
}
public void function2(publish p1,nextshift nx, List<publish> pub)
{
foreach(publish in pub.ToList())
{
//do stuff
}
}
public void function3(publish p1,nextshift nx, List<publish> pub)
{
foreach(publish in pub.ToList())
{
//do stuff
}
}
public void function4(publish p1,nextshift nx, List<publish> pub)
{
foreach(publish in pub.ToList())
{
//do stuff
}
}
问题是你在枚举期间修改了集合:你试图添加或删除一些值,或者用新值替换值。这是不允许的。由于我没有您foreach
的代码,因此无法建议适当的sulotuin,但是您可以检查此问题:集合已修改;枚举操作可能无法执行