多线程时不能插入标识列

时间:2014-09-16 15:26:28

标签: c# sql multithreading visual-studio-2012 sql-server-ce-4

我有一个数据迁移工具,直到最近似乎工作得非常好。

我使用Parallel.Foreach运行一组数据行,计算一些要插入到表的新记录中的变量,然后运行一个SQL语句来插入数据。

Parallel.ForEach<DataRow>(dataTable.Rows, row =>
{
     string reference = row["ref"].ToString();
     int version = (int)row["version"];

     string insertStatement = "INSERT INTO Item (Reference, Version) VALUES (@reference, @version)";

     _database.ExecuteCommand(insertStatement, new SqlServerCeParameter[]
     {
         new SqlServerCeParameter("@reference", reference, SqlDbType.NVarChar),
         new SqlServerCeParameter("@version", version, SqlDbType.Int),
     });
});

public void ExecuteCommand(string sql, SqlServerCeParameter[] parameters)
{
    //create the command that will execute the Sql
    using (var command = new SqlCeCommand(sql, _connection))
    {
        //add any parameters
        if (parameters != null) command.Parameters.AddRange(parameters.Select(p => p.ParameterBehind).ToArray());

        try
        {
            //open the connection 
            if (_connection.State == ConnectionState.Closed) _connection.Open();

            //execute the command
            command.ExecuteNonQuery();
        }
        catch (SqlCeException ex)
        {
            //only catch if the native error is the duplicate value exception otherwise throw as normal
            if (ex.NativeError != 25016) throw;
        }
        finally
        {
            //explicitly close command
            command.Dispose();
        }
    }
}

但是我得到一个聚合异常,其内部异常如下:

{"The column cannot contain null values. [ Column name = ID,Table name = Item ]"}

表的结构如下:

CREATE TABLE Item
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
    Reference NVARCHAR(50) NOT NULL,
    Version INT NOT NULL
);

现在我不明白这个错误,因为ID是一个标识列。

有人认为,由于多线程,它无法同时计算两个ID,但这似乎是一个非常脆弱的原因,因为SqlServerCe对多用户环境来说是好的。

2 个答案:

答案 0 :(得分:1)

重要说明: SQL CE对象不是线程安全的。您在每次通话中使用_connection,我猜是SqlCeConnection的单个实例?

建议每个线程使用自己独立的连接,而不是跨多个线程共享。因此,请尝试在SqlCeConnection方法中创建新的ExecuteCommand,然后每次都进行连接。

这可能无法实现您希望/期望的速度增加但是我不确定多线程是否像您期望的那样工作。您需要多个核心/处理器才能实现这一目标,这本身就是一个深层次的主题。

答案 1 :(得分:0)

确保表格的IDENTITY_INSERT为ON。