Should DbConnection be closed if use clause is used?

Possible duplicate:
Will I use a database connection lock?

Does db.Close() not exist in the following?

 using (DbConnection db = GetDbConnection()) { // do data-access stuff // ... db.Close(); } 
+7
source share
5 answers

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

No, there is no need to close DbConnection if the use clause is used?

and

Yes, this is not necessary here, because using the ends of the connection will mean closing and freeing all memory.

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

But if some lines are after a close line, then it’s useful

 using (DbConnection db = GetDbConnection()) { // do data-access stuff // ... db.Close(); //Useless } 

But here is useful

 using (DbConnection db = GetDbConnection()) { // do data-access stuff // ... db.Close(); //Useful // Some more code } 

In this case, you can do

 using (DbConnection db = GetDbConnection()) { // do data-access stuff // ... } // Some more code which was previously inside using section. 
+9
source

Just to make sure I 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 an implementation of SqlConnection , which inherits from DbConnection . As you can see, this.Close () method exists :)

+4
source

For what I know, when the Dispose() method is called, Close() is executed automatically.
Therefore db.Close(); not required here.

+2
source

Dispose() is called in the closing bracket.

I think in DbConnection the Dispose method also checks if the connection is closed. So no, this is probably not necessary, but I personally think that this is good practice and improves readability, and it does not affect performance, because Close will be called anyway.

+1
source

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

 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 implementation of the method. He will close the connection.

+1
source

All Articles