【问题标题】:Does SqlConnection get disposed using this functionSqlConnection 是否使用此函数进行处理
【发布时间】:2015-11-13 16:25:53
【问题描述】:
public CategorieEquipement Select(int NoType)
{
        SqlConnection cx = new SqlConnection(WebConfigurationManager.ConnectionStrings["SQLConnect"].Connection    String);
        SqlDataReader reader;

        CategorieEquipement lstCategorie = new CategorieEquipement();
        try
        {
            cx.Open();
            SqlCommand com = new SqlCommand("SELECT_CategorieEquip", cx);
            com.CommandType = System.Data.CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@where",NoType);
            reader = com.ExecuteReader();

            while (reader.Read())
            {
                lstCategorie.CodeRef = reader["CodeRef"].ToString();
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine("SELECT ERROR : " + ex.ToString());
            return null;
        }
        finally
        {
            if (cx != null)
            {
                cx.Close();
            }
        }
        return lstCategorie;
    }
}

我的问题是,如果我删除 finally 代码块,垃圾收集器会在处理 SQlConnection 对象时关闭连接吗?

我知道明确表达是一种更好的做法,但我的同事不同意。

【问题讨论】:

  • 你的同事错了
  • 为什么不包装Sql Objects around a using(){} 以利用自动处理的优势.. GC 也不总是即时的.. 我也同意@Steve 也许你不需要依赖你的奶牛工人给你有缺陷的建议/信息
  • 为什么不让它保持原样,代码看起来非常好......

标签: c# dispose sqlconnection


【解决方案1】:

垃圾收集器在处理垃圾时会关闭连接吗? SQLConnection 对象?

垃圾收集器不负责在对象上调用Dispose,通常在Finalizer 中调用Dispose,只有这样GC 才能正确 处理该对象。

需要注意的重要一点是,您无法预测垃圾回收进程何时运行,因此最好明确地处置对象(实现IDisposable

就数据库连接而言,该方法应尽可能晚地打开并尽可能早地关闭。

在上述情况下cx.Close(); 应该足够了,相反,您也可以调用cx.Dispose但更好的方法 是将SqlConnection 包含在using statement 块中。

这将转化为try/finally 块,它将确保SqlConnection 处置。

【讨论】:

    【解决方案2】:

    垃圾收集器会处理它,但由于它是不确定的,你不知道它什么时候会处理它。

    C#提供using结构来处理非托管代码,推荐使用:

    using (SqlConnection cx = new SqlConnection(WebConfigurationManager.ConnectionStrings["SQLConnect"].ConnectionString);)
    {
    
    }
    

    告诉您的同事,他们应该将任何实现 IDisposable 接口的对象实例包装在 using 中,以便以确定性方式处理它们,以确保正确管理应用程序资源并避免内存等问题泄漏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-08
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多