c# sql what to dispose

后端 未结 6 1254
南旧
南旧 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:54

    Do I need to dispose the SqlDataReader since it is within the try catch block?

    -- Yes, as being inside of the try catch will not call the dispose method.

    Do I need to run both cmd.Dispose and cmd.Connection.Close or does one infer the other?

    -- Yes, you need to run both. Calling Cmd.dispose does not close the connection.

    The dispose method is meant to be used by the programmer to clean up resources which either aren't directly managed by the garbage collector, or the need to be cleared out after the program is done using them to free up space. Technically, one could set up the program so the GC would handle it's disposal, but that's an assumption I wouldn't make, especially since the programmer writing the class exposed the dispose method for you. Putting the Command in a using statement is probably the easiest route, because you know it will get disposed when the code leaves the declaration space.

    using (var connection  = new Connection ())
    {
       using (var cmd = new Command())
       {
    
    
    
       }
    }
    

提交回复
热议问题