Why call SqlClient.SqlDataReader Close() method anyway?

前端 未结 8 863
执笔经年
执笔经年 2020-12-15 06:48

Is the SqlClient.SqlDataReader a .NET managed object or not? Why do we have to call the Close() method explicitly close an open connection? Shouldn\'t running out of scope f

相关标签:
8条回答
  • 2020-12-15 07:35

    @Lieutenant Frost

    As a rule in our shop, we explicitly wrap all database calls in a Try...Finally block, with the finally section catching and closing the data connections. It's worth the tiny bit of effort to save yourself a major troubleshooting headache.

    I have a similar rule, but I require that objects implementing IDisposable use the 'using' block.

    using (SqlConnection conn = new SqlConnection(conStr))
    {
         using (SqlCommand command = new SqlCommand())
         {
            // ETC
         } 
    }
    

    The using block calls Dispose immediately when leaving the scope, even with an exception.

    0 讨论(0)
  • 2020-12-15 07:35

    Also take into consideration what happens when an exception gets thrown - you never know if the connection will be closed if you suddenly are forced out of the executing code.

    As a rule in our shop, we explicitly wrap all database calls in a Try...Finally block, with the finally section catching and closing the data connections. It's worth the tiny bit of effort to save yourself a major troubleshooting headache.

    0 讨论(0)
提交回复
热议问题