doing cleanup in Dispose() when implementing IDisposable

  • Thread starter Thread starter Narshe
  • Start date Start date
N

Narshe

If I implement IDisposable in a custom class, how do I let the GC know
that the custom class objects aren't being used anymore, and are ready
for cleanup?

Do I just set them equal to null? Do I need to call GC.Collect() after?

Is IDisposable only meant for objects that already implement it like
sockets and stream?

Thanks.
 
So, there really is no point in implementing IDisposable then? No need
to set the objects to null at all?
 
Narshe said:
So, there really is no point in implementing IDisposable then? No need
to set the objects to null at all?

If your object holds some sort of resources that you'd like the user of your
object to be able to free then you should implement dispose. For example if
your object grabbed a bitmap of the screen when it was created then you
might implement dispose so that the bitmap is destroyed.

Michael
 
Think of a case when your class encapsulates unmanaged resources like a
file handle. You need to close (dispose) this file handle when you
don't need it any more. The GC can't help you with unmanaged resources
since it don't know how to dispose them. The first place you could
think of to put the statement to close the file handle is the Finalize
method (in C#, use destructor). GC will call Finalize to give the
object a last chance to clean up itself before it gets collected.

However, the GC does not guarantee when it will collect a particular
piece of garbage. Thus, you should provide users with a way to
explicitly close the file handle instead of relying on the
indeterminate nature of the GC. That is where the IDisposable interface
comes into the picture. C# even provide the "using" keyword to make
using it more easy.

Guidelines on how to implement IDisposable interface could be found in
the link on my prev post.

Thi
 
Narshe... IDisposable is meant for _exception safe_ deterministic
cleanup of resources and is the eqivalent of RAII (Resource Acquisition
Is Initialization) in C++. It only works properly if you use it in
concert with the using syntax.

So you can either do:

Program p = null;
try
{
p = new Program();
p.SayHello();
Console.WriteLine(p.I);
}
finally
{
if (p != null)
{
p.Dispose();
p = null;
}
}

or just:

using (Program p = new Program())
{
p.SayHello();
Console.WriteLine(p.I);
}

http://www.geocities.com/jeff_louie/oop26.htm

Regards,
Jeff
 
Back
Top