我正在将ForEach替换为Parallel.ForEach。 ForEach工作正常,并给出预期的结果,与Parallel.ForEach产生意外结果。
string[] ids= { };
string input="AA;AA;111;T#BB;BB;222;T#CC;CC;333;F";
string typeId, type, value;
typeId= type=value=string.Empty;
bool isValid = false;
if (input.Contains("#"))
{ ids = input.Split('#'); }
else
{ ids = new string[] { input };}
//using ForEach ,it's working fine,datas are inserted in DB table properly.
foreach (var id in ids)
{
if (id.Contains(";"))
{
var IdInfo = id.Split(';');
if (IdInfo[0] != null)
{
typeId = Info[0];
}
if (IdInfo.Length >= 2)
{ type = IdInfo[1]; }
if (IdInfo.Length >= 3)
{ value = IdInfo[2]; }
if (IdInfo.Length >= 4)
{ isValid = IdInfo[3]=="T" ? true:false; } // T=true
}
else
{
return;
}
DBInsertMethod("someuniqueId", typeId, type, value, isValid);
}
我已经用Parrallel.ForEach替换了同一段代码
Parallel.ForEach ( ids,(id)=>
{
if (id.Contains(";"))
{
var IdInfo = id.Split(';');
if (IdInfo[0] != null)
{
typeId = Info[0];
}
if (IdInfo.Length >= 2)
{ type = IdInfo[1]; }
if (IdInfo.Length >= 3)
{ value = IdInfo[2]; }
if (IdInfo.Length >= 4)
{ isValid = IdInfo[3]=="T" ? true:false; } // T=true
}
else
{
return;
}
DBInsertMethod("someuniqueId", typeId, type, value, isValid);
});
现在同一行在表中插入了三遍。任何建议/建议都值得赞赏。
最佳答案
实际上,即使Paralle.Foreach创建了多个线程来处理并行处理,某些变量也会在其作用域之外声明,因此它们是唯一的。
尝试在lambda中声明它们:
Parallel.ForEach ( ids,(id)=>
{
string typeId, type, value;
typeId= type=value=string.Empty;
bool isValid=false;
if (id.Contains(";"))
{
var IdInfo = id.Split(';');
if (IdInfo[0] != null)
{
typeId = Info[0];
}
if (IdInfo.Length >= 2)
{ type = IdInfo[1]; }
if (IdInfo.Length >= 3)
{ value = IdInfo[2]; }
if (IdInfo.Length >= 4)
{ isValid = IdInfo[3]=="T"; } // T=true
}
else
{
return;
}
DBInsertMethod("someuniqueId", typeId, type, value, isValid);
});
关于c# - Parallel.ForEach无法按预期的方式运行C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49189388/