Why call SqlClient.SqlDataReader Close() method anyway?

前端 未结 8 870
执笔经年
执笔经年 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:32

    The 'managed' resource referred to by the term 'managed code' is memory. That's it. Any other scarce resource needs to be wrapped with the disposable pattern, including database connections.

    The reason this is a problem for you is that the garbage collector doesn't run for every object the moment it goes out of scope. It's much more efficient to collect more items less frequently. So if you wait for the collector to dispose your objects (and yes, if you implement idisposable it eventually will) you maybe be holding a number of database connections open much longer than you realize.

提交回复
热议问题