c# - 数据库连接是否被 SqlConnection 类的析构函数关闭?

标签 c# ado.net 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/

相关文章:

c# - Dart,对泛型的限制?

c# - 合并两个数据表

c# - 打开SQL连接时算术溢出异常

c# - 使用已经打开的数据库连接

c# - 使用 linq 查询检查 Null 条件的问题

c# - Microsoft Bot Framework System.ArgumentException : 'EncryptedText is not properly formatted'

C# 排序列表 : How to get the next element?

oracle - 对 EntityFramework 和 ado.net 存储过程使用相同的事务

c# - 并行加载到 DataSet 有什么问题吗?

c# - 使用 sql 身份验证的 sql 连接字符串