是否使用此函数处理 SqlConnection

Does SqlConnection get disposed using this function

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 对象时关闭连接吗?

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

will the garbage collector close the connection when disposing of the SQlConnection object?

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

需要注意的一件重要事情是,您无法预测垃圾收集过程何时会 运行,因此最好显式处理对象 (实现 IDisposable

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

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

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

垃圾回收会处理它,但由于它是不确定的,您不知道它何时会处理。

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

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

}

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