From my understanding, .Net will pool SqlConnection
objects where the connection string is the same by default. Will the connection still be pooled if I call the Dispose method?
This question is asked under the context of an ASP.NET application that at times makes many hits to the database in a single PageLoad
event. I want the connections to be pooled, but would like confirmation that Closing and Disposing of the connection once the data operation is complete does not interfere with .NET's handling of the connection pool.
You reuse a prior database connection, in a new context to avoid the cost of setting up a new database connection for each request. The primary reason to avoid using database connections is that you're application's approach to solving problems isn't structured to accommodate a database connection pool.
While there may be many instances (like on SqlConnection) where you call Disponse() on some object and it simply calls Close() on it's connection or closes a file handle, it's almost always your best bet to call Dispose()! unless you plan on reusing the object in the very near future.
Close() will simply close the connection to the server as defined in the connection string. The Connection can be used/re-opened after this point. Connection. Dispose() will clean up completely, removing all unmanaged resources preventing that Connection from being used again.
When using connection pooling, closing a SqlConnection
simply tells the connection pool that you are done with it. The pool will then decide whether or not to actually close the connection, or to reuse it.
From the MSDN docs:
If the SqlConnection goes out of scope, it won't be closed. Therefore, you must explicitly close the connection by calling Close or Dispose. Close and Dispose are functionally equivalent. If the connection pooling value Pooling is set to true or yes, the underlying connection is returned back to the connection pool. On the other hand, if Pooling is set to false or no, the underlying connection to the server is closed.
The MSDN documentation on SQL Server Connection Pooling says
Connections are released back into the pool when they are closed or disposed
and
We strongly recommend that you always close the connection when you are finished using it so that the connection will be returned to the pool. You can do this using either the Close or Dispose methods of the Connection object ...
Also, it is the connection pooler that will determine if the connections are dropped from the pool
The connection pooler removes a connection from the pool after it has been idle for a long time, or if the pooler detects that the connection with the server has been severed
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