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

[亡魂溺海] 提交于 2019-11-28 00:18:45

问题


This question already has an answer here:

  • Close and Dispose - which to call? 7 answers

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

  • Close()
  • Dispose()

Same for the SQLiteDataReader object.

What is the difference ?


回答1:


Dispose also closes the connection if it hasn't been closed, but when calling Close, you can reopen the connection again. This is not possible when the connection is disposed.

In general, don't call Close, but simply call dispose implicitly by wrapping the creation of a connection in a using block:

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



回答2:


Connection.Close() will simply close the connection to the server as defined in the connection string. The Connection can be used/re-opened after this point.

Connection.Dispose() will clean up completely, removing all unmanaged resources preventing that Connection from being used again. Once disposed is called you shouldn't try to use the object any more. Within Dispose(),Close()` will all most certainly be called too.

I would recommend using the using syntax like so if possible, to ensure things are cleaned up correctly:

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

This will automatically dispose of the connection for you, regardless of an exception being thrown.



来源:https://stackoverflow.com/questions/17168839/what-is-the-difference-between-connection-close-and-connection-dispose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!