What is the difference between connection.Close () and connection.Dispose ()?

I noticed that the SQLiteConnection object in System.Data.SQLite has two similar methods:

  • Close()
  • Dispose()

The same goes for the SQLiteDataReader object.

What is the difference?

+7
source share
2 answers

Dispose also closes the connection if it was not closed, but when you call Close you can open the connection again. This is not possible if the connection is established.

In general, do not call Close , but simply call dispose implicitly by wrapping the connection in the using block:

 using (var connection = new SqlConnection(...)) { // use connection here. } // connection gets closed and disposed here. 
+17
source

Connection.Close () will simply close the connection to the server as defined in the connection string. After this connection, the connection can be used / reopened.

Connection.Dispose() completely clear itself by deleting all unmanaged resources that prevent it from reusing the connection. When called, you should not try to use the object anymore. Inside Dispose(), Close () `all of this will certainly be called.

I would recommend using using syntax, if possible, to make sure things are cleaned correctly:

 using(SqlLiteConnection conn = new SqlLiteConnection(...)) { // Do work here } 

This will automatically delete the connection for you, no matter which exception is thrown.

+5
source

All Articles