Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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();
}
like image 214
CJ7 Avatar asked Aug 20 '12 07:08

CJ7


3 Answers

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.
like image 93
Nikhil Agrawal Avatar answered Nov 02 '22 11:11

Nikhil Agrawal


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

like image 39
Michal Franc Avatar answered Nov 02 '22 10:11

Michal Franc


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

like image 38
Marco Avatar answered Nov 02 '22 12:11

Marco