【问题标题】:Benefits of "using" block for SqlCommand initializationSqlCommand 初始化的“使用”块的好处
【发布时间】:2015-02-24 23:40:29
【问题描述】:

我理解从应用程序连接到 sql server 时使用 using 块的概念,因为它会在连接超出范围时立即关闭连接,从而节省我们编写 try catch finally 块的时间。

但我的问题是,在初始化 SqlCommand 时使用 using 有什么好处吗?通常我会这样做:

string cs = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;

using(SqlConnection con = new SqlConnection(cs))
{
    SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.City", con);

        con.Open();

        DropDownList1.DataSource =  cmd.ExecuteReader();
        DropDownList1.DataTextField = "City";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();
}

但是,通过将 SqlCommand 初始化放入 using block,我可以获得哪些可能的好处?

string cs = ConfigurationManager.ConnectionStrings["CS1"].ConnectionString;

using(SqlConnection con = new SqlConnection(cs))
{
    using(SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.City", con))
    { 
        con.Open();
        DropDownList1.DataSource =  cmd.ExecuteReader();
        DropDownList1.DataTextField = "City";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();
    }
}

我在网上搜索的所有材料都谈到了连接一旦超出范围就会关闭,是的,我明白这一点,但是将 SqlCommand 放在 using 块中会不会提高效率?

非常感谢任何建议或指示,谢谢。

【问题讨论】:

    标签: c# asp.net .net sql-server .net-4.5


    【解决方案1】:

    查看源代码可以清楚地看到这一点。

    这是SqlCommand.Dispose的实现:

    override protected void Dispose(bool disposing) 
    {
        if (disposing) 
        {
            _cachedMetaData = null;
        }
    
        base.Dispose(disposing);
    }
    

    如您所见,这并没有多大作用。但是,在查看base.Dispose 时:

    public void Dispose() 
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    

    SqlCommand 继承自 DbCommand,而 DbCommand 又继承自 ComponentComponent 实现了一个finalizer,这意味着一旦没有人引用它,对象就不会被释放,因为它仍然有对finalizer queue 的引用。

    当你用using 语句包装SqlCommand 时,最重要的部分是它的基类(组件)调用GC.SupressFinialize,它删除了对终结器队列的引用并让对象被收集一次GC 开始了。

    这就是SqlCommand 实现IDisposable 的原因,应该被处理掉。

    【讨论】:

    • 谢谢你的回答,非常感谢:)
    猜你喜欢
    • 2012-01-18
    • 2010-12-08
    • 2015-06-04
    • 2012-10-02
    • 1970-01-01
    • 2011-01-12
    • 2017-09-16
    • 2011-11-09
    相关资源
    最近更新 更多