简体   繁体   English

SqlConnection池似乎不起作用

[英]SqlConnection pooling doesn't seem to work

I'm trying to optimize my code performance accessing SQL Server 2014 database and noticed that connection pooling doesn't seem to work as advertised by ADO.NET. 我正在尝试优化访问SQL Server 2014数据库的代码性能,并注意到连接池似乎不像ADO.NET所宣传的那样起作用。 By default it's supposed to be enabled and working out of the box (as long as same connection string is used). 默认情况下,应该启用它并且可以直接使用它(只要使用相同的连接字符串)。 My experiments are showing however that opening/closing connection on SqlConnection does in fact cause Audit Login / Logout to be raised. 但是,我的实验表明,在SqlConnection上打开/关闭连接确实会导致审核登录/注销升高。

As per https://msdn.microsoft.com/en-us/library/vstudio/8xx3tyca(v=vs.100).aspx this should not be the case: 根据https://msdn.microsoft.com/zh-CN/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. 这是因为将连接返回到连接池后实际上并未关闭。

My simple test was to create a console app, similar to the following: 我的简单测试是创建一个控制台应用程序,类似于以下内容:

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();
}

Running this code yeilds results captured by Sql Profiler similar to the following. 运行此代码将使Sql Profiler捕获的结果与以下类似。 Observer the multiople login/logout events which should have not been captured if pooling was working as advertised. 观察多池登录/注销事件,如果池按公布的方式工作,则不应捕获这些事件。 I've been able to reproduce this on multiple machines (Windows 8/10, .NET 4.5, Sql Server 2014 Developer Edition). 我已经能够在多台计算机(Windows 8/10,.NET 4.5,Sql Server 2014 Developer Edition)上重现此内容。

在此处输入图片说明

Main question: How do I get connection pooling to work. 主要问题:如何使连接池正常工作。

If sp_reset_connection is issued then connection pooling is enabled. 如果发出sp_reset_connection,则启用连接池。 See What does sp_reset_connection do? 请参见sp_reset_connection做什么?

To see if an Audit Login is pooled or non-pooled in the Profiler, you need to add EventSubClass column to the Trace and check the Audit Login and Audit Logout events. 要查看事件探查器中是否存在池化或非池化审核登录,您需要在跟踪中添加EventSubClass列,并检查审核登录和审核注销事件。 The new column will show either "1 - Nonpooled" or "2 - Pooled". 新列将显示“ 1-非池”或“ 2-池”。 In your example only the first connection has "1 - Nonpooled", the next 2 Audit Logins have EventSubClass = "2 - Pooled". 在您的示例中,只有第一个连接具有“ 1-非池”,接下来的2个审计登录具有EventSubClass =“ 2-池”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM