<分区>
如果我丢失了对包含打开的数据库连接的对象的引用,当 GC 清理我的对象时(即通过 SqlConnection 类
的析构函数)是否关闭了连接?
还是导致连接泄漏?
<分区>
如果我丢失了对包含打开的数据库连接的对象的引用,当 GC 清理我的对象时(即通过 SqlConnection 类
的析构函数)是否关闭了连接?
还是导致连接泄漏?
最佳答案
它在 Dispose
中关闭,而不是在析构函数 (Finalize
) 中关闭。所以使用 using
语句,你就安全了。
很难找到文档(不要依赖反编译的程序集)但最终我在 SqlConnection.Close
中找到了它:
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.
....
The following example creates a SqlConnection, opens it, displays some of its properties. The connection is automatically closed at the end of the using block.
此外:
注意
Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition.
来源(ILSpy、.NET 4):
// System.Data.SqlClient.SqlConnection
protected override void Dispose(bool disposing)
{
if (disposing)
{
this._userConnectionOptions = null;
this._poolGroup = null;
this.Close(); // <-------
}
this.DisposeMe(disposing);
base.Dispose(disposing);
}
关于c# - 数据库连接是否被 SqlConnection 类的析构函数关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24557056/