c# - 是否使用此函数处理 SqlConnection

标签 c# dispose sqlconnection

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在一个物体上,通常是 Dispose在 Finalizer 中被调用,只有这样 GC 才能正确处置该对象。

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

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

在上面的例子中cx.Close();应该够了,相反,你也可以调用cx.Dispose , 但更好的方法 是将 SqlConnection 括起来在 using statement堵塞。

这将转化为 try/finally block ,它将确保 SqlConnection处理。

关于c# - 是否使用此函数处理 SqlConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33697361/

相关文章:

c# - 如何创建具有非线性刻度的 slider ?

dispose - 必须为接口(interface) 'System.IDisposable' 实现 Sub Dispose()

.net - MemoryStream 必须明确处理?

c# - 如何通过一次调用来依次运行sql语句

c# - using 语句外的 SQL 连接构造函数

c# - 未处理的异步异常

c# - 从 C# 调用 python 函数

dart - 检查无状态小部件是否在 flutter 中处理

asp-classic - 连接超时不起作用

C# - UPDATE SET WHERE 查询问题 (OleDb)