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/