【问题标题】:Closing SqlConnection and SqlCommand c#关闭 SqlConnection 和 SqlCommand c#
【发布时间】:2011-03-23 04:11:29
【问题描述】:

在我的 DAL 中,我编写如下查询:

using(SQLConnection conn = "connection string here")
{
    SQLCommand cmd = new ("sql query", conn);
    // execute it blah blah
}

现在我突然想到我没有明确关闭 SQLCommand 对象。现在我知道“使用”块会处理 SQLConnection 对象,但这也会处理 SQLCommand 对象吗?如果不是那么我有一个严重的问题。我将不得不在成千上万行代码上的 SQLCommand 上添加“使用”,或者在数百种方法上执行 cmd.Close()。请告诉我,如果输入 using 或 close 命令会为 Web 应用程序提供更好的内存管理?

【问题讨论】:

标签: c# ado.net garbage-collection using-statement


【解决方案1】:

不,using 语句不会处理命令。

您也应该使用 using 语句包装命令,因为这将正确地调用它们上的 Dispose

using(SQLConnection conn = 'connection string here')
{
    using(SQLCommand cmd = new ('sql query', conn))
    {
        //execute it blah blah
    }
}

【讨论】:

    【解决方案2】:

    它不会处理SqlCommand,但SqlCommand最终由垃圾收集器处理。我倾向于做以下事情:

    using (SqlConn conn ... )
    using (SqlComm comm ... )
    {
        conn.Open();
    }
    

    在这里堆叠 using 语句将同时处理这两种情况。

    【讨论】:

      【解决方案3】:

      SqlConnection不知道SqlCommand,所以你应该自己关闭它:

      using (SqlConnection conn = new SqlConnection("connection string here"))
      using (SqlCommand cmd = new SqlCommand("sql query", conn))
      {
          // execute it blah blah
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-06
        • 2018-03-27
        • 1970-01-01
        • 1970-01-01
        • 2013-06-03
        • 2011-05-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多