Best way to close Access Jet OledbConnection

喜夏-厌秋 提交于 2020-01-07 02:32:09

问题


In my winform application - framework 3.5 sp1 - I have a custom Data-Reader. I have to choose the way to close the connection

First way:

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

Second way:

Public Sub Open()
    Dim cn As New OleDb.OleDbConnection(sConnectionString)
    cn.Open()

    ' ...

End Sub

Public Sub Close()

    ' ...

End Sub

In the second way is the Garbage Collector that close the connection. What is better? Thank you! Pileggi


回答1:


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.

From MSDN:

Garbage collection occurs when one of the following conditions is true:

The system has low physical memory.

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.

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.

If you call cn.close you should use a try catch finally block to be sure the connection always closes even on exception.




回答2:


Best is to use using block, it will dispose the object as soon as you move out of the block.

You MUST NEVER WAIT for GC to close db connection. We can never predict the time of execution of GC collecting objects.



来源:https://stackoverflow.com/questions/8518996/best-way-to-close-access-jet-oledbconnection

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