c# - 在处理 SQLConnection 之前,我是否必须 Close() ?

标签 c# asp.net using sqlconnection sqlcommand

根据我的其他 question here about Disposable objects ,我们应该在 using block 结束之前调用 Close() 吗?

using (SqlConnection connection = new SqlConnection())
using (SqlCommand command = new SqlCommand())
{
    command.CommandText = "INSERT INTO YourMom (Amount) VALUES (1)";
    command.CommandType = System.Data.CommandType.Text;

    connection.Open();
    command.ExecuteNonQuery();

    // Is this call necessary?
    connection.Close();
}

最佳答案

由于您有一个 using block ,因此将调用 SQLCommand 的 Dispose 方法并关闭连接:

// System.Data.SqlClient.SqlConnection.Dispose disassemble
protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}

关于c# - 在处理 SQLConnection 之前,我是否必须 Close() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1195829/

相关文章:

c# - 将类型库导入为 C# 代码的工具

c# - 如何动态加载 DLL 并在其中使用类(实现已知接口(interface))[C#]

c# - 在我的 WCF 服务上调用 close() 会释放所有资源吗?

c# - C#获取数组的商和余数

asp.net - ASMX Web 服务 - 返回具有属性的用户定义的类

c# - 如何确保 StringBuilder 对象在多线程环境中被 GCed? (鉴于我不能使用 using 关键字)?

include - #using、#include 和 'assembly references'——它们是什么以及它们之间的关系?

ASP.NET/IIS7.5写入日志文件不起作用(权限,UAC,配置,???)

c# - StackExchange.ConnectionMultiplexer.GetServer 不工作

c# - 在 using block 中使用 'as IDisposable'