SqlConnection 池似乎不起作用
SqlConnection pooling doesn't seem to work
我正在尝试优化访问 SQL Server 2014 数据库的代码性能,并注意到连接池似乎不像 ADO.NET 宣传的那样工作。默认情况下,它应该被启用并且开箱即用(只要使用相同的连接字符串)。然而,我的实验表明 opening/closing 连接 SqlConnection 实际上会导致审计登录/注销被提升。
根据https://msdn.microsoft.com/en-us/library/vstudio/8xx3tyca(v=vs.100).aspx,情况不应如此:
Login and logout events will not be raised on the server when a connection is fetched from or returned to the connection pool. This is because the connection is not actually closed when it is returned to the connection pool.
我的简单测试是创建一个控制台应用程序,类似于以下内容:
var conn = new SqlConnection("Data Source=(local);Integrated Security=SSPI;Initial Catalog=icedb;");
for (int i = 0; i < 3; i++)
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = "select 1";
cmd.ExecuteScalar();
conn.Close();
}
运行 此代码生成由 Sql Profiler 捕获的结果,类似于以下内容。观察多个 login/logout 事件,如果池化如所宣传的那样工作,这些事件应该不会被捕获。我已经能够在多台机器(Windows 8/10、.NET 4.5、Sql Server 2014 Developer Edition)上重现此内容。
主要问题:如何让连接池工作。
如果发出 sp_reset_connection 则启用连接池。参见 What does sp_reset_connection do?
要查看审计登录在探查器中是池化还是非池化,您需要将 EventSubClass 列添加到跟踪并检查审计登录和审计注销事件。新列将显示“1 - Nonpooled”或“2 - Pooled”。
在您的示例中,只有第一个连接具有“1 - Nonpooled”,接下来的 2 个审核登录具有 EventSubClass =“2 - Pooled”。
我正在尝试优化访问 SQL Server 2014 数据库的代码性能,并注意到连接池似乎不像 ADO.NET 宣传的那样工作。默认情况下,它应该被启用并且开箱即用(只要使用相同的连接字符串)。然而,我的实验表明 opening/closing 连接 SqlConnection 实际上会导致审计登录/注销被提升。
根据https://msdn.microsoft.com/en-us/library/vstudio/8xx3tyca(v=vs.100).aspx,情况不应如此:
Login and logout events will not be raised on the server when a connection is fetched from or returned to the connection pool. This is because the connection is not actually closed when it is returned to the connection pool.
我的简单测试是创建一个控制台应用程序,类似于以下内容:
var conn = new SqlConnection("Data Source=(local);Integrated Security=SSPI;Initial Catalog=icedb;");
for (int i = 0; i < 3; i++)
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = "select 1";
cmd.ExecuteScalar();
conn.Close();
}
运行 此代码生成由 Sql Profiler 捕获的结果,类似于以下内容。观察多个 login/logout 事件,如果池化如所宣传的那样工作,这些事件应该不会被捕获。我已经能够在多台机器(Windows 8/10、.NET 4.5、Sql Server 2014 Developer Edition)上重现此内容。
主要问题:如何让连接池工作。
如果发出 sp_reset_connection 则启用连接池。参见 What does sp_reset_connection do?
要查看审计登录在探查器中是池化还是非池化,您需要将 EventSubClass 列添加到跟踪并检查审计登录和审计注销事件。新列将显示“1 - Nonpooled”或“2 - Pooled”。 在您的示例中,只有第一个连接具有“1 - Nonpooled”,接下来的 2 个审核登录具有 EventSubClass =“2 - Pooled”。