views:

311

answers:

3

What would happen if you call Close() on a SqlConnection object before you call Close() on a SqlDataReader using that connection?

Actually, what I really want to know is whether or not the order in which you Close them matters. Does calling SqlConnection.Close() completely close the connection, or will it remain open if you do not call Close() on a SqlDataReader using that connection?

Sorry for the multiple questions, but I don't think I really understand how connection closing works.

+11  A: 

It'll close the connection (returns it to the pool) and SqlDataReader would throw an exception (System.InvalidOperationException) in case it's used afterward.

Mehrdad Afshari
Very fast response +1
ichiban
So is there any reason to bother closing the SqlDataReader if you're just going to close the SqlConnection right afterwards? It sounds like it is safe to close only the SqlConnection. Is that so?
Ender
@Ender, the right way to do so is to close it. It just doesn't feel good to close the connection. Probably, you should be using `using` statements anyway.
Mehrdad Afshari
@Mehrdad Cool, thanks. I'm working on someone else's code, and wanting to make sure I really understand what is going on. This helps a lot!
Ender
+8  A: 

Rather than worrying about the order on how to close them, why not wrap them in using statements.

// the following code has parts left out for brevity...
using(var conn = new SqlConnection( ... ))
using(var cmd = new SqlCommand( ... ))
{
    conn.Open();

    using(var reader = cmd.ExecuteReader())
    {
        // do whatever with the reader here...
    }
}

the using statements ensure that your objects are closed, and in the correct order if you nest them accordingly. See http://msdn.microsoft.com/en-us/library/yh598w02.aspx for more info.

Scott Ivey
+2  A: 

The actual database connection will be closed (returned to the pool) when you close/dispose the SqlConnection object, so the database resources are safe.

However, you should close/dispose the SqlDataReader also, otherwise it will keep a reference to the SqlConnection object, keeping them both in memory. Eventually the finalizer will dispose the SqlDataReader object if you don't do it, and then the SqlConnection object can also be collected, but you have no control over when that happens.

The SqlDataReader can be partially usable after you have closed the connection, but nothing that you really can rely on. It still has some data in it's buffer, so some operations may work, but anything that requires more data from the database will cause an exception.

Guffa
Cool, thanks for the detailed explanation.
Ender