Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why call SqlClient.SqlDataReader Close() method anyway?

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 for such an object automatically close this? Shouldn't garbage collector clean it up anyway?

Please help me understand what is the best practise here.

I have seen a related question here and it further illustrates the issue I have with a web application. The issue is that we were running out of connections. The detailed error is here:

Exception: System.InvalidOperationException
Message: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
Source: System.Data 

at  System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection(SqlConnectionString options, Boolean& isInTransaction)
at  System.Data.SqlClient.SqlConnection.Open()

To fix this, I had to explicitly close all the SQLDataReader objects.

I am using .NET Framework 3.5

like image 894
Julius A Avatar asked Oct 30 '08 14:10

Julius A


1 Answers

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

like image 54
wprl Avatar answered Oct 06 '22 16:10

wprl