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

筅森魡賤 提交于 2019-12-01 21:03:56

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.

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.

It may not be necessary in a lot of cases, but it's best practice for a reason. There's no reason to let resources persist beyond the point where they are no longer useful. The using construct helps ensure this.

Isn't it just a matter of you freeing the resource now vs. garbage collection freeing it later?

There's a difference. If you create 2 of those readers without opening/closing the connection, but don't dispose of the first one before using the second, you'll get a conflict saying the connection is already associated to an open reader.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!