Why call SqlClient.SqlDataReader Close() method anyway?

前端 未结 8 893
执笔经年
执笔经年 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-15 07:34

    Sure, it will be collected when it goes out of scope (if their are no other references to it). When it is collected, it will be closed through its Dispose() method. However, you never really know when the GC is going to deallocate things; if you don't close your readers, you very quickly run out of available connections to the database.

    Further Reading

    • O'Reilly's ADO.NET Connection Pool Explained
    • Microsoft's Retrieving Data using a DataReader has a general overview of DataReaders.

    ~ William Riley-Land

提交回复
热议问题