freeing database connections and other critical resources

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,
What is the best method to close database connections? Is
it enough if we just use the Close() method. Does the
connection get released immediately? or do we have to do
anything in the Dispose and Finalize methods? Your replies
are appreciated. Thanks in advance.
 
Close is enough, that will release the connection back into the pool.

You do not need to call dispose.
 
The best method to close a database connection, by far, is with the 'using'
keyword:

using (SqlConnection conn = new SqlConnection(...))
{
// use connection here
}

This guarantees that Dispose() will be called for the connection when the
control exits the scope of the using statement. Most importantly, the call
to Dispose is guaranteed no matter how you exit the scope - even if there is
an exception.

SqlConnection.Dispose() calls SqlConnection.Close() which puts the physical
SQL connection back to the connection pool so it can be reused later.

Other classes that wrap critical (unmanaged) resources usually implement
IDisposable and they should also be used inside a 'using' statement whenever
possible.

Sami
www.capehill.net
 
Back
Top