Is there any need to close a DbConnection if a usi

2019-01-27 20:17发布

问题:

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();
}

回答1:

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.


回答2:

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



回答3:

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



回答4:

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.



回答5:

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.