Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is closing/disposing an SqlDataReader needed if you are already closing the SqlConnection?

I noticed This question, but my question is a bit more specific.

Is there any advantage to using

using (SqlConnection conn = new SqlConnection(conStr))
{
     using (SqlCommand command = new SqlCommand())
     {
        // dostuff
     } 
}

instead of

using (SqlConnection conn = new SqlConnection(conStr))
{
     SqlCommand command = new SqlCommand();
     // dostuff
}

Obviously it does matter if you plan to run more than one command with the same connection, since closing an SqlDataReader is more efficient than closing and reopening a connection (calling conn.Close();conn.Open(); will also free up the connection).

I see many people insist that failure to close the SqlDataReader means leaving open connection resources around, but doesn't that only apply if you don't close the connection?

like image 893
Brian Avatar asked Nov 29 '22 05:11

Brian


2 Answers

Technically it's not needed; closing a SqlConnection should destroy any resources that the SqlDataReader is using. The reverse is also true; you don't need to Dispose the SqlConnection if you dispose a SqlDataReader that was created with CommandBehavior.CloseConnection.

Practically speaking, though, when a class implements IDisposable, you should Dispose it when you're finished with it. The implementation details of framework classes are subject to change at any time, and unless the documentation specifically outlines circumstances under which it is not necessary to Dispose the instance, there is always a possibility that some future change/update will result in your code having a resource leak.

It's really no extra effort - so just wrap it in a using block.

like image 44
Aaronaught Avatar answered Dec 05 '22 07:12

Aaronaught


In my opinion, there are two rules to follow here:

  1. Classes that implement IDisposable should be wrapped in a using block.
  2. You should not rely on a class's implementation of IDisposable to ignore rule 1.

That is, even if you know that disposing the connection object took care of disposing its associated command object, you should not rely on this behavior.

By the way, it's possible to nest using blocks in a cleaner fashion:

using (SqlConnection conn = new SqlConnection(conStr))
using (SqlCommand command = new SqlCommand())
{
    // dostuff
}

and I would use

SqlCommand command = conn.CreateCommand();

instead of creating a new SqlCommand and then associating it with the connection.

like image 182
Jamie Ide Avatar answered Dec 05 '22 05:12

Jamie Ide