Does closing a database connection in Dispose method is right?

断了今生、忘了曾经 提交于 2020-01-20 04:14:44

问题


I've had a suspicion that a database connection used in one of our applications is not always closed. I went to see the code and I've found a class DataProvider that has SqlConnection object. The connection is opened in the constructor of this class and closed in it's Dispose method (don't judge that, I know keeping an open connection is evil, it's just not my code and it's not the point of the question anyway). The Dispose method is implemented like this:

protected virtual void Dispose(bool disposing)
{
    if (!_disposed)
    {
        if (disposing)
        {
            if (_conn != null)
                _conn.Close();
        }

        _disposed = true;
    }
}

The question is:
Does it always guarantee that the connection is closed?
Is this code right?

I think there should be _conn.Dispose() called - am I right and could it affect not closing the connection (probably not)?


回答1:


Dispose is never called automatically.

The connection will not be closed until the Dispose method of your object is explicitly called, or if your class in used in a using() block

A safer way is to call the dispose method in your finalizer and ensure the finalizer is suppressed when the Dispose method is called.

This article present the correct way to implement the pattern

Hope it helps !

Cédric




回答2:


conn.Dispose(); will also close the connection, so can't hurt changing it to follow the dispose pattern.

But there functionally equivalent so there must be a problem else where.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx

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.



来源:https://stackoverflow.com/questions/1016800/does-closing-a-database-connection-in-dispose-method-is-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!