首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在SQLConnection被释放之前,我必须关闭()吗?

在SQLConnection被释放之前,我必须关闭()吗?
EN

Stack Overflow用户
提问于 2009-07-28 18:21:57
回答 7查看 43.7K关注 0票数 121

根据我的另一个question here about Disposable objects,我们应该在using块结束之前调用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();
}
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2009-07-28 18:26:17

由于您有一个using块,因此将调用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);
}
票数 112
EN

Stack Overflow用户

发布于 2009-07-28 18:28:07

使用.NET Reflector实现SqlConnection的反汇编

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }

    this.DisposeMe(disposing);
    base.Dispose(disposing);
}

它在Dispose()内部调用Close()

票数 26
EN

Stack Overflow用户

发布于 2009-07-28 18:29:59

使用Reflector,您可以看到SqlConnectionDispose方法实际上调用了Close()

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this._userConnectionOptions = null;
        this._poolGroup = null;
        this.Close();
    }
    this.DisposeMe(disposing);
    base.Dispose(disposing);
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1195829

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档