w0051977
w0051977

Reputation: 15817

.NET Memory leaks and best practice

What is the best way to write functions in Microsoft.NET (VB) to avoid memory leaks. I have always followed this style:

Public Sub TestMemoryLeak()
        Dim testCon As SqlConnection
        Try
            testCon = New SqlConnection
        Catch

        Finally
            If testCon.State = ConnectionState.Open Then
                testCon.Close()
            End If
            testCon = Nothing
        End Try
    End Sub

Here the connection reference is created before the TRY clause and is initialised after the TRY clause. I believe the connection is always closed and dereferenced even if an exception is thrown. Is this good practice? I see a lot of code that creates references and dereferences in the TRY clause, but this would mean that the memory is not correctly handled if an exception is thrown. Some developers say they don't like to clean up in the finally clause. I do not fully understand why.

Upvotes: 0

Views: 2257

Answers (1)

SLaks
SLaks

Reputation: 888283

You should just use the Using statement:

Using testConn As New SqlConnection(...)
    ...
End Using

This will compile to a Finally that will dispose in all circumstances.

Upvotes: 6

Related Questions