lamarmora
lamarmora

Reputation: 1126

Best way to close Access Jet OledbConnection

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

Upvotes: 0

Views: 651

Answers (2)

Jay
Jay

Reputation: 6017

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.

Upvotes: 2

Maheep
Maheep

Reputation: 5605

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.

Upvotes: 3

Related Questions