连接池已用尽

时间:2016-06-06 14:13:48

标签: c# npgsql

使用并行foreach将数据插入数据库时​​出现以下错误:

  

连接池已用尽'

将一些数据插入数据库后

try
{
    var connection = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;

    Parallel.ForEach(Enumerable.Range(0, 1000), (_) =>
    {
        using (var connectio = new NpgsqlConnection(connection))
        {
            connectio.Open();
            using (var command = new NpgsqlCommand("fn_tetsdata", connectio) { CommandType = CommandType.StoredProcedure })
            {
                command.Parameters.AddWithValue("firstname", "test");
                command.Parameters.AddWithValue("lastname", "test");
                command.Parameters.AddWithValue("id", 10);
                command.Parameters.AddWithValue("designation", "test");

                command.ExecuteNonQuery();
            }
            connectio.Close();
        }
    });
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

2 个答案:

答案 0 :(得分:4)

Constrain the amount of parralelism with MaxDegreeOfParallelism, by default it could be exceeding the number of DB connections you have. Find a balance between parallelising your work and not killing the DB :)

Sub Background_Lists()
a = 0
Range("E4:E2004").Clear
Range("B4:B2004").Value = Range("=Parts!B18:B2018").Value
Range("D4:D2004").Value = Range("=[B.xlsx]Sheet1!A2:A2002").Value
For i = 4 To 2004
    If Cells(i, 4).Value >= 300000 Then
        Cells(4 + a, 5).Value = Cells(i, 4).Value
        a = a + 1
    End If
Next i

答案 1 :(得分:2)

我假设您正在使用并行性来提高性能。如果是这种情况,那么首先需要一个基线。串行运行1,000个查询,每次创建一个新连接(实际上只从池中拉出一个)。

然后使用相同的连接对象进行尝试,看看性能是否有所改善。

然后使用来自命令对象尝试它,只需更改参数值。

然后使用相同的连接并行尝试,你没有创建1,000个连接对象,你已经尝试过了。

如果通过使用并行性获得显着的性能改进,我会感到惊讶,因为Parallel提高了 CPU绑定任务和数据查询的性能I / O通常比CPU更受约束。

相关问题