C# – connection leak issue in SQL Server

ado.netcnetsql serversql-server-2008

I am using 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). 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).

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?

thanks in advance,
George

Best Answer

Not so, the ADO.NET connection pool will return your connection to the pool after Close is called. 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();