有没有办法计算池中使用了多少个连接

时间:2012-03-30 09:55:36

标签: .net connection-pooling

我想写这样的东西,

在我的单元测试中我想知道是否存在连接泄漏? 所以我想从之前得到池连接的数量,并且它应该相等,测试是STA,所以它必须工作

所以,问题是这个

的标题

2 个答案:

答案 0 :(得分:0)

我不知道这是否是你要找的,但试一试。

SELECT COUNT(*) AS Number_Of_Connections FROM sys.dm_exec_sessions WHERE program_name='your connection str application name'

或基于数据库名称计数

SELECT DB_NAME(dbid) as 'DbNAme', COUNT(dbid) as 'Connections' from master.dbo.sysprocesses with (nolock) WHERE dbid > 0 GROUP BY dbid

答案 1 :(得分:0)

您应该可以执行以下示例控制台应用程序:

    static void Main(string[] args)
    {
        using (SqlConnection conn = new SqlConnection(@"SAMPLE_CONNECTIONSTRING"))
        {
            conn.Open();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = conn;
                cmd.CommandText = "SELECT * FROM SAMPLE_TABLE";
                SqlDataReader dr = cmd.ExecuteReader();

                //Used to show that values update based on connections in use.
                //dr.Dispose();
                //cmd.Dispose();
                //conn.Dispose();

                //create our WMI searcher
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_PerfRawData_NETDataProviderforSqlServer_NETDataProviderforSqlServer");
                //now loop through all the item found with the query
                foreach (ManagementObject obj in searcher.Get())
                {
                    try
                    {
                        Console.WriteLine("Class Win32_PerfRawData_NETDataProviderforSqlServer_NETDataProviderforSqlServer");
                        Console.WriteLine(obj.Properties["Name"].Value);

                        Console.WriteLine("Connection Pools " + obj.Properties["NumberOfActiveConnectionPools"].Value);
                        Console.WriteLine("Pooled Connections " + obj.Properties["NumberOfPooledConnections"].Value);
                        Console.WriteLine("Active Connections " + obj.Properties["NumberOfActiveConnections"].Value);
                        Console.WriteLine("Free Connections " + obj.Properties["NumberOfFreeConnections"].Value);
                    }
                    catch (Exception ex)
                    {
                        //throw new Exception("Failed to enumerate a WMI command.", ex);
                    }
                }
            }
        }
        Console.ReadLine();
    }

VB Code Sample that got me the correct Win32 class.