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
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:
If you call cn.close you should use a try catch finally block to be sure the connection always closes even on exception.