c# - Parallel.Foreach C# 随机结果

标签 c# mysql

我想从数据集中读取所有结果并通过 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/

相关文章:

c# - 单击按钮激活/停用 javascript

c# - 如何对 HH :MM:SS format time strings in C#? 进行除法

c# - StaticFileOptions.OnPrepareResponse 不会为 index.html 调用

mysql - 当查询在 delphi 中选择 varchar 数据类型的列时打开 MySQL 查询

python - Pandas 数据帧 to_sql 数据长度超过 65536 个字符

mysql - 将此 MySQL 查询转换为 PyGreSQL

java - Jpa查询右连接

c# - 将 SqlConnection 传递给类会在处理后丢失其连接字符串

c# - Unity3D C# - 无法将类型 `string' 隐式转换为 `int'

php - MySQL 算作最高请求,限制为 5