在Dispose方法中关闭数据库连接是否正确?

在Dispose方法中关闭数据库连接是否正确?

问题描述:

我怀疑我们的应用程序中使用的数据库连接并不总是关闭。我去看代码,我发现一个类DataProvider有SqlConnection对象。连接在这个类的构造函数中打开,并在它的Dispose方法中关闭(不要判断,我知道保持开放连接是邪恶的,它只是不是我的代码,它不是问题的问题)。 Dispose方法实现像这样:

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). Dispose method is implemented like this:

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

                _disposed = true;
            }
        }

问题是:它总是保证连接关闭了?这个代码是正确的吗?我想应该有_conn.Dispose()调用 - 我是对的,它可以影响不关闭连接(可能不是)?

The question is: does it always guarantee that the connection is closed? And 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)?

Dispose从不会自动调用。

Dispose is never called automatically.

在显式调用对象的Dispose方法之前,连接将不会关闭, ()块

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

一种更安全的方法是在您的终结器中调用dispose方法,并确保在调用Dispose方法时禁止终结器。

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

本文介绍正确的实施方法

希望它有帮助!

Cédric