C# connection.Close() 和 connection.Dispose() 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17168839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the difference between connection.Close() and connection.Dispose()?
提问by Epoc
I noticed that the SQLiteConnectionobject in System.Data.SQLiteowns two similar methods :
我注意到该SQLiteConnection对象System.Data.SQLite拥有两个类似的方法:
Close()Dispose()
Close()Dispose()
Same for the SQLiteDataReaderobject.
同为SQLiteDataReader对象。
What is the difference ?
有什么不同 ?
采纳答案by Steven
Disposealso 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.
Dispose如果连接尚未关闭,也会关闭连接,但在调用 时Close,您可以再次重新打开连接。这在处理连接时是不可能的。
In general, don't call Close, but simply call dispose implicitly by wrapping the creation of a connection in a usingblock:
通常,不要调用Close,而只是通过将连接的创建包装在using块中来隐式调用 dispose :
using (var connection = new SqlConnection(...))
{
// use connection here.
} // connection gets closed and disposed here.
回答by Ian
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.Close() 将简单地关闭与连接字符串中定义的服务器的连接。在此之后可以使用/重新打开连接。
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.
Connection.Dispose()将完全清理,删除所有非托管资源,防止再次使用该连接。一旦被调用,您就不应再尝试使用该对象。在Dispose(),Close()` 中肯定也会被调用。
I would recommend usingthe using syntax like so if possible, to ensure things are cleaned up correctly:
using如果可能的话,我会推荐使用语法,以确保正确清理:
using(SqlLiteConnection conn = new SqlLiteConnection(...))
{
// Do work here
}
This will automatically dispose of the connection for you, regardless of an exception being thrown.
无论抛出异常,这都会自动为您处理连接。

