c#sql要处置什么

Pet*_*teT 5 c# sql

我有下面的代码来查询存储过程中的记录,但我担心我可能不会处理我需要或正在处理的对象将在不久之后被垃圾收集器清除.

我是否需要处理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();
            }

        }

    }
Run Code Online (Sandbox Code Playgroud)

Dav*_*d M 18

您应该丢弃数据读取器和命令.如果丢弃命令,则无需单独关闭连接.理想情况下,您应该使用using块:

using (SqlCommand cmd = new...)
{
    // do stuff
    using (SqlDataReader dr = cmd.ExecuteReader())
    {
        // do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您需要异常处理,请在使用块内部或周围单独执行 - 不需要最终用于Dispose调用using.

  • 处置`SqlCommand`对象将不会**处理`SqlConnection`.这很容易测试.http://stackoverflow.com/questions/60919/is-sqlcommand-dispose-enough/60934#60934 (2认同)