c# sql what to dispose

后端 未结 6 1223
南旧
南旧 2021-01-06 00:10

I have the code below to query records from a stored procedure but am concerned I may not be disposing what I need to or am disposing when the object would be cleared by the

6条回答
  •  离开以前
    2021-01-06 00:46

    You should dispose the data reader, and the command. No need to separately close the connection if you dispose the command. You should ideally do both using a using block:

    using (SqlCommand cmd = new...)
    {
        // do stuff
        using (SqlDataReader dr = cmd.ExecuteReader())
        {
            // do stuff
        }
    }
    

    If you need exception handling do that separately either inside or around the using blocks - no need for the finally for the Dispose calls though with using.

提交回复
热议问题