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.
You should just use the
Usingstatement:This will compile to a
Finallythat will dispose in all circumstances.