Barry said:
The Finalize code in the class does not fire until the .exe is closed.
I expected it to fire at either:-
- the point at which oFred is set to Nothing, or
- the point at which we exit from the Sub, and variable oFred goes out of
scope.
Read up on "Garbage Collection" and the "IDisposable" pattern (or
Interface).
The CLR will reclaim only Managed memory /if/ and when it needs to, i.e.
when it needs to allocate some /more/ memory to something else. For a
program as simple as the one you showed, it doesn't need to do so, so
the memory doesn't get reclaimed until the program dies.
Setting objects to Nothing in Visual Basic is [usually] a pointless
exercise. It does /not/ get rid of the object but, instead, just makes
it "eligible" for Garbage Collection which, as I've said, might take a
very long time to run and get rid of the object.
Please Note: This usually /does not/ matter.
You only need to "worry" about it if your class uses any "unmanaged"
resources. A simple example might be a file that you use for munging
data around through some external tool; when your object dies, it really
ought to "tidy up" (delete) its temporary file.
For things like this, implement the IDisposable pattern and have your
"client" code call the object's Dispose() method.
Class X
Implements IDisposable
Sub Finalize()
Me.Dispose( False )
End Sub
Public Sub Dispose()
Implements IDisposable.Dispose
Me.Dispose( True )
' If we've cleaned up after ourselves, we can /lighten/
' GC's load by telling it to /ignore/ this object.
GC.SuppressFinalize( Me )
End Sub
Private Sub Dispose( ByVal disposing as Boolean )
If ( disposing ) Then
' Called from "our" code, we can kill off "related" objects
If ( File.Exists( m_sTemporaryFilePath ) ) Then
File.Kill( m_sTemporaryFilePath )
End If
End If
' Otherwise, we've been called from the finaliser,
' Other objects may or may not exist,
' so we only do our /own/ stuff.
End Sub
End Class
Module Y
Sub Main()
Dim x2 as New X()
x2.DoSomething()
x2.DoSomethingElse()
x2.DoSomethingElseAgain()
' then, the important bit
x2.Dispose()
End Sub
End Module
HTH,
Phill W.