Question: Dispose with shared members

D

demon

I'm having this class

Public Class TestClass
Implements IDisposable


Dim Conn As SqlConnection


Public Sub New(ByVal connectionString As String)
Conn = New SqlConnection(connectionString)
End Sub


Public Function GetDateTime() As DateTime
Dim Cmd As SqlCommand = New SqlCommand("SELECT
GETDATE()", Conn)
If Conn.State <> ConnectionState.Open Then Conn.Open()


Dim Today As DateTime = Cmd.ExecuteScalar()
Cmd.Dispose()
Return Today
End Function


Private disposedValue As Boolean = False ' To
detect redundant calls


' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: free unmanaged resources when
explicitly called
Conn.Dispose()
End If


' TODO: free shared unmanaged resources
End If
Me.disposedValue = True
End Sub


#Region " IDisposable Support "
' This code added by Visual Basic to correctly implement the
disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in
Dispose(ByVal
disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region


End Class


I'm using it through Namespace "My" like this


Namespace My
<Global.Microsoft.VisualBasic.HideModuleName()> _
Public Module MyTestClass
Private _TestClass As New ThreadSafeObjectProvider(Of
Global.TestClass)
Public ReadOnly Property TestClass() As
Global.TestClass
Get
Return _TestClass.GetInstance()
End Get
End Property
End Module
End Namespace


Is it correct to release unmanaged resources like Conn in TestClass by
calling My.TestClass.Dispose() ? When i'm using If Not My.TestClass Is
Nothing Then My.TestClass.Dispose a new instance of the class is
created and then disposed. Is there anything else to do to avoid this ?

is this correct ?


thanks in advance for your answers :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top