正在关闭/处置如果你已经关闭的SqlConnection需要一个SqlDataReader的?

正在关闭/处置如果你已经关闭的SqlConnection需要一个SqlDataReader的?

问题描述:

我注意到这个问题,但我的问题是有点更具体。

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

是否有任何优势,使用

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

而不是

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



显然,不管它,如果你打算运行以上具有相同的连接一个命令,因为关闭一个 SqlDataReader的比关闭和重新打开连接(呼叫 conn.Close()更高效;康恩。开(); 也将腾出的连接)

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).

我看到许多人坚持认为没有关闭 SqlDataReader的表示周围留下打开的连接资源,但是如果你不关闭连接并不只适用?

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?

在我看来,有两个规则在这里如下:

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


  1. 实现IDisposable的类应被包裹在一个使用块。

  2. 您不应该依赖一个类的实现了IDisposable的无视规则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
}

和我会用

SqlCommand command = conn.CreateCommand();



而不是创建一个新的SqlCommand,然后将其与连接相关联。

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