From MSDN:
While the SqlDataReader is being used, the associated SqlConnection is busy serving the SqlDataReader, and no other operations can be performed on the SqlConnection other than closing it. This is the case until the Close method of the SqlDataReader is called. For example, you cannot retrieve output parameters until after you call Close.
a) Why couldn’t you use SqlConnection for anything else? After all, when ExecuteQuery() returns SqlDataReader object, the data from DB has already been retrieved and populated SqlDatareader object. Thus I don’t see how or why SqlConnection should still be serving SqlDataReader object?!
b) More importantly, for what reason would it be bad idea to retrieve output parameters before you call Close() on SqlDataReader?
c) When above quote mentions that no other operations can be performed on SqlConnection, what operations does it have in mind? Just those that would require to connect to remote sql server, or we can’t use any members of SqlConnection instance?
a) When
ExecuteReaderreturns, the data has not all been retrieved and populated in the reader, it may still be streaming back from the database. That’s the whole point of theSqlDataReaderbecause it’s more efficient to do this than to load it all up front.b) You can’t retrieve output parameters until after the reader has finished because of the way the Tabular Data Stream (TDS) protocol is structured. The output parameters are not physically sent down the stream until after the result set data.
c) It means none of the operations except
Closeare documented as being guaranteed to work. Whether they actually do work or not is irrelevant because that is an implementation detail rather than a contract, and programming against implementation details is a recipe for disaster.Why do you want to re-use the connection anyway? The connections that
SqlConnectionuses are pooled behind the scenes, so when you dispose one it doesn’t really get rid of all the resources, it just returns the connection to the pool. This means you can use the connection for the shortest time possible, ideally within ausingblock, and not have to worry about this type of thing. Just create a new connection whenever you need one, and don’t bother trying to re-use them as it’s already happening behind the scenes.