我想从数据集中读取所有结果,并通过Mysql插入一个值,但是插入使我得到随机结果:
Parallel.ForEach(table, new ParallelOptions { MaxDegreeOfParallelism = 2 }, row =>
{
DataRow newrow = BDDestino.newrow("Cars");
newrow["Code"] = row["CODE"];
newrow["Name"] = row["NAME"];
BD.insert(newrow);
});
DataSet / DataTable“表”的内容很大,但是在Mysql表中的插入是随机的。
如果我的行是
1, 2, 3, 4
插入有时是:
2,3
或:>
1,2,3
我需要按顺序排列所有行。
编辑:我认为Parallel.ForEach句子可以快速插入白色顺序,但是我看到Parallel.ForEach本身并没有这样做。就像@juharr所说,这句话可能是最糟糕的。谢谢大家。
最佳答案
如果使用并行性,则不能保证调用.insert()的顺序(如您所发现的)。
您需要以某种方式提前解决该顺序:
使用可以从现有表中预先计算出的数组索引。
DataRow[] bdArray = new DataRow[table.RowCount];
Parallel.ForEach(table, new ParallelOptions { MaxDegreeOfParallelism = 2 }, row =>
{
DataRow newrow = BDDestino.newrow("Cars");
newrow["Code"] = row["CODE"];
newrow["Name"] = row["NAME"];
// Add the new row in a pre-arranged position
int index = table.indexOf(row);
bdArray[index] = newrow;
});
也许没关系……您以后可以随时对其进行排序。
关于c# - Parallel.Foreach C#随机结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33804599/