C# - closing Sql objects best practice

前端 未结 8 1054
陌清茗
陌清茗 2020-12-31 11:29

If you have a C# function with Sqlaccess, is it mandatory to close all objects/handles, or is everything cleaned up automatically once you exit the function

For exam

8条回答
  •  滥情空心
    2020-12-31 11:59

    You don't need to have a separate using statement for the SqlDataReader (as well as one using statement for the connection) unless you plan do perform other operations with the connection after the SqlDataReader has fully read through the row set.

    If you are just opening a connection, reading some data using the reader, and then closing the connection, then one using statement for the entire block of code (surrounding the connection) will suffice as the garbage collector will clean up all resources tied to the connection that is disposed by the first using statement.

    Anyway, here's a good article that describes it all...

提交回复
热议问题