简体   繁体   English

SQL Server中的连接泄漏问题

[英]connection leak issue in SQL Server

I am using SQL Server 2008 Enterprise + C# + ADO.Net + .Net 3.5. 我使用的是SQL Server 2008 Enterprise + C#+ ADO.Net + .Net 3.5。 I am using connection pool at ADO.Net client side (the default behavior of ADO.Net). 我在ADO.Net客户端使用连接池(ADO.Net的默认行为)。 I am using sp_who2 or sys.dm_exec_connections to find active connections numbers (let me know if my method to find active connection numbers are wrong). 我正在使用sp_who2或sys.dm_exec_connections查找活动连接数(如果我找到有效连接数的方法错误,请告诉我)。

If each time after I create and open a new ADO.Net connection object, I will have a matched close statement to close the ADO.Net connection object instance after using the connection object (to execute store procedure), I am wondering in this scenario, the active connection number should always be 0 after I close all connection from my ADO.Net client application, and if show active connection number > 0, it should be very weird? 如果每次创建并打开一个新的ADO.Net连接对象后,我将使用匹配的close语句在使用连接对象后关闭ADO.Net连接对象实例(执行存储过程),我想知道在这种情况下,从我的ADO.Net客户端应用程序关闭所有连接后,活动连接数应始终为0,如果显示活动连接数> 0,它应该是非常奇怪的?

thanks in advance, George 乔治,提前谢谢

Close will free the connection to be available for the connection pool . 关闭将释放连接以用于连接池 It doesn't mean the physical connection is closed. 这并不意味着物理连接已关闭。

Also make sure the .close is in a finally, so it executes both on the regular flow and when an exception occurs. 还要确保.close在finally中,因此它在常规流和异常发生时执行。

Make sure that you properly close or dispose the SqlConnection . 确保正确关闭或处置SqlConnection Disposing a connection will automatically close it. 处置连接将自动关闭它。

using(SqlConnection connection = new SqlConnection(connectionString))
{
} //The connection will close automatically here

But you can be explicit and still do a .Close() before the end of the using. 但是你可以明确地在使用结束之前做一个.Close()。

You can also clear all pending connection that have the status Awaiting Command by calling 您还可以通过调用清除状态为Awaiting Command的所有挂起连接

SqlConnection.ClearAllPools();

Not so, the ADO.NET connection pool will return your connection to the pool after Close is called. 不是这样,ADO.NET连接池将在调用Close后返回到池的连接。 The connection may not really be closed at this point. 此时连接可能不会真正关闭。 To force the connection to be closed try clearing the pool before closing. 要强制关闭连接,请在关闭之前清除池。 Try this and you should see the connection close from the server. 试试这个,你应该看到从服务器关闭连接。

var conn = new SqlConnection("a server goes here");
        conn.Open();

        SqlConnection.ClearAllPools();
        conn.Close();

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

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