Parallel.For 与 Npgsql 一起使用吗?

LeM*_*sel 3 c# postgresql parallel-processing npgsql

是否可以将 Npgsql 函数与Parallel.For块一起使用?

这是我的示例,但出现异常“后端发送了无法识别的响应类型:\0”

    NpgsqlConnection PGconnexion = new NpgsqlConnection(...);
    string SqlParallel = "";
    int OID = -1;
    Parallel.For(0, 100, i =>
    {
        SqlParallel = string.Format(@"INSERT INTO ParallelTest(Id) VALUES({0}) RETURNING OID;", i);
        using (NpgsqlCommand PGcommandParallel = new NpgsqlCommand(SqlParallel, PGconnexion)) 
        {
            try { OID = (int)PGcommandParallel.ExecuteScalar(); }
            catch (Exception ex) { Console.WriteLine(ex.Message); }
        }
        Console.WriteLine("Insert: {0} OID: {1}", i, OID);
    });
Run Code Online (Sandbox Code Playgroud)

和 PostgreSql 表架构

-- Table: paralleltest

-- DROP TABLE paralleltest;

CREATE TABLE paralleltest
(
  id integer
)
WITH (
  OIDS=TRUE
);
GRANT ALL ON TABLE paralleltest TO public;
Run Code Online (Sandbox Code Playgroud)

Fra*_*ior 5

基督教!

Npgsql 与其他提供程序一样,不是线程安全的。当您使用具有相同连接的多个线程时,您最终会遇到此问题。

为了使其工作,您必须将创建连接的行放入 Parallel.For 循环内:

    string SqlParallel = "";
    int OID = -1;
    Parallel.For(0, 100, i =>
    {
       using (NpgsqlConnection PGconnexion = new NpgsqlConnection(...))

       {
            SqlParallel = string.Format(@"INSERT INTO ParallelTest(Id) VALUES({0}) RETURNING OID;", i);
            using (NpgsqlCommand PGcommandParallel = new NpgsqlCommand(SqlParallel, PGconnexion))
            {
                 try { OID = (int)PGcommandParallel.ExecuteScalar(); }
                 catch (Exception ex) { Console.WriteLine(ex.Message); }
             }
             Console.WriteLine("Insert: {0} OID: {1}", i, OID);
         } 
     });
Run Code Online (Sandbox Code Playgroud)

我在这里测试了一下,效果很好。请尝试一下,如果您对此更改仍有问题,请告诉我。请注意,我使用了“using”子句,因此块完成后连接就会关闭。

我希望它有帮助。