关闭Access Jet OledbConnection的最佳方法 [英] Best way to close Access Jet OledbConnection
问题描述
在我的winform应用程序 - framework 3.5 sp1 - 我有一个自定义数据读取器。我必须选择关闭连接的方式。
In my winform application - framework 3.5 sp1 - I have a custom Data-Reader. I have to choose the way to close the connection
第一种方式:
Private cn As OleDb.OleDbConnection = Nothing
Public Sub Open()
cn = New OleDb.OleDbConnection(sConnectionString)
cn.Open()
' ...
End Sub
Public Sub Close()
' ...
cn.Close()
cn.Dispose()
End Sub
方式:
Public Sub Open()
Dim cn As New OleDb.OleDbConnection(sConnectionString)
cn.Open()
' ...
End Sub
Public Sub Close()
' ...
End Sub
第二种方式是关闭垃圾收集器连接。什么更好?
谢谢!
Pileggi
In the second way is the Garbage Collector that close the connection. What is better? Thank you! Pileggi
推荐答案
一般来说,你应该关闭你自己打开的每一个连接。垃圾收集不会给你任何保证,当它会发生。您可能会开发泄漏并阻止未来的查询执行。
Generally speaking, you should close every connection you open yourself. Garbage collection won't give you any guarantees about when it will happen. You will likely develop leaks and block future query execution.
从 MSDN :
当以下条件之一为
时, true:
Garbage collection occurs when one of the following conditions is true:
系统物理内存低。
被管理堆
超过可接受的阈值。这意味着在托管堆上已经超过了
可接受的内存使用的阈值。这个
阈值在进程运行时不断调整。
The memory that is used by allocated objects on the managed heap surpasses an acceptable threshold. This means that a threshold of acceptable memory usage has been exceeded on the managed heap. This threshold is continuously adjusted as the process runs.
调用GC.Collect方法。在几乎所有情况下,你没有
调用这个方法,因为垃圾收集器连续运行。
此方法主要用于独特的情况和测试。
The GC.Collect method is called. In almost all cases, you do not have to call this method, because the garbage collector runs continuously. This method is primarily used for unique situations and testing.
如果调用cn.close, finally块确保连接总是关闭,即使异常。
If you call cn.close you should use a try catch finally block to be sure the connection always closes even on exception.
这篇关于关闭Access Jet OledbConnection的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!