Destroying a class

davele

Member
Joined
Sep 29, 2009
Messages
12
Programming Experience
5-10
I have a class that has timers and logic that I want to "Kill". Performing a TestClass = Nothing does not destroy it (calling it form a form).

Any ideas?

Thanks
 
You should implement the IDisposable interface in your class and then perform the necessary cleanup in the Dispose method. You then call Dispose to destroy an instance. Note that "destroy" is a relative term. The object still exists in memory until the garbage collector cleans it up for good but, as long as you implement your Dispose method properly, all disposable resources will be disposed and you want have to worry about anything carrying on in the background once you're finished with the object.

Here's a simple example of implementing the IDisposable interface on a class that contains a Timer. Note that I have highlighted the lines that I added myself. All the rest is added by the IDE when you added the Implements line and hit Enter.
VB.NET:
Public Class SomeClass
    Implements IDisposable

    [COLOR="Red"]Private clock As New Timer[/COLOR]

    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 other state (managed objects).
                [COLOR="Red"]Me.clock.Dispose()[/COLOR]
            End If

            ' TODO: free your own state (unmanaged objects).
            ' TODO: set large fields to null.
            [COLOR="Red"]Me.clock = Nothing[/COLOR]
        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
 
Great information. I really appreciate you taking the time, it's helped me out a ton. Works like a charm! Anything I should be weary of though when it comes to Garbage Collection? What happens if I re-create the object before the garbage collector has disposed of it?

Thanks again.
 
Back
Top