Is there any need to close a DbConnection if a usi

2019-01-27 20:44发布

Possible Duplicate:
Will a using block close a database connection?

Is db.Close() unnecessary in the following?

using (DbConnection db = GetDbConnection())
{
   // do data-access stuff
   // ...

   db.Close();
}

5条回答
神经病院院长
2楼-- · 2019-01-27 20:53

Is there any need to close a DbConnection if a using clause is used?

No, there is no need to close a DbConnection if a using clause is used?

and

Yes it is unnecessary in here because when scope of using ends, connection will dispose meaning closing and releasing all memory.

Since DBConnection implements IDisposable interface, close function is there in the Dispose method of DBConnection.

But if some lines are after close line then it is useful

using (DbConnection db = GetDbConnection())
{
  // do data-access stuff
  // ...

  db.Close(); //Useless
}

But here it is useful

using (DbConnection db = GetDbConnection())
{
  // do data-access stuff
  // ...

  db.Close(); //Useful

 // Some more code
}

In that case you can do

using (DbConnection db = GetDbConnection())
{
  // do data-access stuff
  // ...

}

// Some more code which was previously inside using section.
查看更多
Explosion°爆炸
3楼-- · 2019-01-27 20:54

For what I know, when Dispose() method is called, Close() is automatically performed.
So db.Close(); is not necessary here.

查看更多
孤傲高冷的网名
4楼-- · 2019-01-27 20:55

Just to be sure i have checked the code :)

   protected override void Dispose(bool disposing)
    {
      if (disposing)
      {
        this._userConnectionOptions = (DbConnectionOptions) null;
        this._poolGroup = (DbConnectionPoolGroup) null;
        this.Close();
      }
      this.DisposeMe(disposing);
      base.Dispose(disposing);
    }

This is the implementation of SqlConnection which is inheriting from DbConnection. As you can see there is this.Close() method :)

查看更多
姐就是有狂的资本
5楼-- · 2019-01-27 21:13

At the closing brace the Dispose() is called.

I think in the DbConnection the Dispose method will also check if the connection is closed. So no, it probably isn't necessary, but I personally think it is good practice and improves readability and it doesn't affect performance because the Close will be called one way or another.

查看更多
不美不萌又怎样
6楼-- · 2019-01-27 21:14

Extracted code from the dispose implementation of the SqlConnection (Derived of DbConnection) class:

public void Dispose()
{
   Dispose(true);
}

protected override void Dispose(bool disposing)
{
  if (disposing)
  {
     this.Close();
  }
  base.Dispose(disposing);
}

The using keyword uses the IDisposable interface. The method above is the method implementation. It will close the connection.

查看更多
登录 后发表回答