簡體   English   中英

Parallel.Foreach C#隨機結果

[英]Parallel.Foreach C# random results

我想從數據集中讀取所有結果,並通過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; }); 

也許沒關系……您以后可以隨時對其進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM