简体   繁体   English

Parallel.Foreach C#随机结果

[英]Parallel.Foreach C# random results

I want to read all result from a Dataset and insert a value by Mysql, but the insert take me random result: 我想从数据集中读取所有结果,并通过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); 
});

The content of the DataSet/DataTable"table" is great, but the insert in the Mysql table is random. DataSet / DataTable“表”的内容很大,但是在Mysql表中的插入是随机的。

If my rows are 如果我的行是

1, 2, 3, 4

The insert sometimes is: 2,3 插入有时是: 2,3

or: > 1,2,3 或:> 1,2,3

I need ALL rows in order. 我需要按顺序排列所有行。

Edit: I thought that Parallel.ForEach sentences can insert whit order and very fast, but i see that Parallel.ForEach doesn't do it itself. 编辑:我认为Parallel.ForEach句子可以快速插入白色顺序,但是我看到Parallel.ForEach本身并没有这样做。 Like @juharr says, this sentence maybe can be worst. 就像@juharr所说,这句话可能是最糟糕的。 Thanks to all. 谢谢大家。

If you use parallelism, you cannot guarantee the order in which .insert() is called (as you found). 如果使用并行性,则不能保证调用.insert()的顺序(如您所找到的)。

Somehow you need to fix that order in advance: 您需要以某种方式提前修复该顺序:

  • Use array indexes, which can be pre-calculated from the existing table. 使用可以从现有表中预先计算出的数组索引。

     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; }); 

Or maybe it doesn't matter... you can always sort them afterwards. 也许没关系……您以后可以随时对其进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM