基本上我尝试使用任务一起运行四个功能。 这四个函数运行自己的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
}
}
答案 0 :(得分:0)
问题是您在枚举期间修改了集合:您尝试添加或删除某些值,或者用新值替换值。这是不允许的。由于我没有foreach
的代码,因此无法建议适当的sulotuin,但您可以查看以下问题:
Collection was modified; enumeration operation may not execute