【发布时间】:2010-11-12 14:53:19
【问题描述】:
我有下面的代码来从存储过程中查询记录,但我担心我可能不会处理我需要的东西,或者当垃圾收集器不久之后将清除对象时我正在处理。
是否需要处理 SqlDataReader,因为它位于 try catch 块中?
我需要同时运行 cmd.Dispose 和 cmd.Connection.Close 还是一个推断另一个?
垃圾收集器最终会处理掉所有这些对象(可能不够及时),还是因为使用了非托管代码而隐含地需要处理这些对象?
public void GetData(string studentID)
{
SqlCommand cmd = new SqlCommand("sp_stored_proc",
new SqlConnection(Settings.Default.connectionString))
{ CommandType = CommandType.StoredProcedure };
try
{
cmd.Connection.Open();
cmd.Parameters.AddWithValue("@student_id", studentID);
SqlDataReader dr = cmd.ExecuteReader();
//do something with the data
if (dr != null)
dr.Dispose();
}
catch
{
//error handling
}
finally
{
if (cmd != null)
{
cmd.Dispose();
cmd.Connection.Close();
}
}
}
【问题讨论】: