So implementing this interface means what? That when the client calls
.Dispose method on my object, I'll release whatever needs to be released?
Yep.
How is that different from writing a ReleaseResources method where I
release all the resources?
There is no difference. IDisposable is just a formalized interface to
accomplish this. Basically, it is a convention.
So should I set local objects to Nothing or not? What about class level
variables that I no longer need?
Local objects don't need to be set to nothing because once the object is
out of scope and no longer referenced it is eligable for GC. In fact,
the JIT can actually optimize the code so that an local object is available
for GC even before the end of the method... Say you have this scenario:
Private Sub MySub()
Dim o As New MyObjectType
o.DoCoolStuff()
' Do a lot of stuff that doesn't have anything to do with o
End Sub
Because the method no longer referes to o, the JIT will make it
available for GC as soon as the call to DoCoolStuff is complete... It
seems in the Beta days setting the object to nothing could actually
interfere with this optimization - but I have since read that the JIT
will actually optimize away the assignment to nothing now.
For class level objects, it would probably be a good idea when they are
no longer needed.
Also, how is Finalize different?
Finalize is a method of object. It's purpose is essentially the same as
Dispose - release resources. The difference is that Finalize is called
by the GC, and should be avoided because it can have a negative impact
on the performance of the GC, because it actually takes two passes to
clean up an object that has overridden Finalize.
What you will usually see is that objects that contain unmanaged
resources will usually implement both IDisposable AND override finalize.
The Dispose implementation, will usually call GC.SuppressFinalize to
remove the object from the finalization queue. This way, you can make
sure that your resources will be released eventually - even if the
client forgets to call dispose. But if they do remember, then you don't
incure the performance hit.
One thing I've taken to doing lately, is actually throw an exception
from the finalize method (or you could use an assertion). This sort of
clues me in to when I haven't managed my resources properly
Thanks, this is good stuff. However, is it me or they made it a lot
more complicated than it needs to be? You pass true or false into
Dispose based on the identity of the caller??????? What? Was someone
smoking at ms? I am starting to miss the lack of backspace in vi.
Just covering the bases. For the most part, resource management is
pretty nice in .NET because the runtime can do most of the work for
you... Unfortunately, ever system has it's drawbacks, and there are
times when you have to take a more active role in the process