I understand that if I instantiate a SqlConnection object, I am really grabbing a connection from a connection pool. When I call Open(), it will open the connection. If I call the Close() or Dispose() method on that SqlConnection object, it is returned to the connection pool.
However, that doesn't really tell me if it's really closed, or if I still have an active connection to the database.
How can I force a SqlConnection to close at the network level, or at least tell when it closes?
Example:
using(SqlConnection conn = new SqlConnection(DBConnString)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); ... cmd.ExecuteReader(CommandBehavior.CloseConnection); ... }
If the connection was TRULY closing, the second and third runs should also be 300 ms. But I know that the connection is not truly closed for those runs (I checked the SQL Server's activity monitor). It doesn't take the extra 200ms to perform authentication/etc.
How do I force the connection to truly close?
Ideas
References
The sqlConnection will close the connection after it will pass using block and call Dispose method.
Yes, certainly you need to close the pooled connection as well. It's actually a wrapper around the actual connection. It wil under the covers release the actual connection back to the pool.
The following are four parameters that control most of the connection pooling behavior: Connect Timeout- controls the wait period in seconds when a new connection is requested, if this timeout expires, an exception will be thrown. Default is 15 seconds. Max Pool Size- specifies the maximum size of your connection pool.
You can disable Pooling by adding 'Pooling=false' to the connection string. In such case, a connection will be deleted from memory and free the session.
Maybe SqlConnection.ClearPool
?
Moe Sisko's answer (Call SqlConnection.ClearPool
) is correct.
Sometimes you need a connection to really close rather than return to the pool. As an example, I have a unit test that creates a scratch database, builds the schema, tests some stuff, then drops the scratch database if the tests all pass.
When connection pooling is active, the drop database command fails because there are still active connections. From the point of view of programmer all SQLConnections are closed, but as the pool still holds one open, SQL Server won't allow the drop.
The best documentation for how connection pooling is handled is this page on SQL Server Connection Pooling on MSDN. One doesn't want to turn connection pooling off entirely because it improves performance with repeated opens and closes, but sometimes you need to call a "force close" on an SQLConnection so that it will let go of the database.
This is done with ClearPool. If you call SqlConnection.ClearPool(connection)
before closing/disposing, when you do close/dispose it will really go away.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With