Thursday, July 2, 2009

SqlConnection.Dispose vs. SqlCommand.Dispose

After reviewing the service layer of an application to verify that all SqlConnections were properly being cleaned up, I thought I would post my findings on the details of how the SqlCommand and SqlConnection objects work with ADO.Net connection pooling.

I found several blogs/threads that stated "calling dispose on a SqlCommand instance will in turn clean up the underlying connection and remove it from the ADO.Net connection pool". This is not quite the case. I put performance monitor on task, and while watching NumberOfActiveConnections and NumberOfPooledConnections, it was clear that the active connection was never closed by calling SqlCommand.Dispose(). A review of MSDN documentation on the dispose method simply states: "Releases all resources used by the Component. (Inherited from Component.)".

To ensure that the active connection is in fact closed, and returned to the connection pool, you must call either Close() or Dispose() on the SqlConnection instance. It is recommended to call Dispose() since this also releases other instance level resources (such as the connection string). Note that even when calling Dispose, the connection is returned to the ADO.Net connection pool.

You can accomplish this same functionality by wrapping your connection/command in using statements, the underlying connection management is the same, and this accomplishes calling the Dispose() method on both the connection and command.