.NET sql 个连接超过最大池大小

.NET sql connections exceeding max pool size

我写了一个简单的应用程序来测试连接字符串中的 Max Pool Size=50。

    static void Test1()
    {
        string connectionString = @"Server=.;Database=appsdb;Trusted_Connection=True;Application Name=JH;Max Pool Size=50";
        for (int i = 1; i <= 100; i++)
        {
            var conn = new SqlConnection(connectionString);
            conn.Open();
            using (var cmd = new SqlCommand("select newid()", conn))
            {
                using (var r = cmd.ExecuteReader())
                {
                    while (r.Read())
                    {
                        Console.WriteLine($"[{Thread.CurrentThread.ManagedThreadId}] {i} - {r.GetGuid(0)}");
                    }
                }
            }
        }
        Console.WriteLine("Done");
        Console.ReadLine();
    }

我最初有 51 个连接 运行 预计第 51 个连接会失败,但它没有。
它始终在 71st 连接失败,但出现以下异常:

System.InvalidOperationException: 'Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.'

当我检查 sp_who(或 sp_who2)时,我可以看到恰好有 50 个连接。真是莫名其妙。
我能理解 .NET 是否以某种方式让您重用连接 但为什么在第 71 位?
为什么只允许额外的 20 个(逻辑)连接?为什么不是 19 或 47?

您似乎没有保持 for 循环迭代之间的连接。这意味着每次迭代 for 循环时,来自前一次迭代的连接都符合垃圾回收条件,这会将 底层 连接释放回池中。所以:大概发生了垃圾收集。要对此进行测试:保持使用的连接可访问 - 将它们放在列表或类似列表中。例如:

var list = new List<SqlConnection>();
for (int i = 1; i <= 100; i++)
{
    var conn = new SqlConnection(connectionString);
    list.Add(conn);
    conn.Open();
    // ... etc removed
}
GC.KeepAlive(list);