IDisposable with managed code


M

Mark

If your class implements IDisposable, I was told that this increases the
speed with which your class is garbage collected. Is this true? And if so,
how much "time" does it save? Assume that we are dealing with 100% managed
code and that the clean-up is of big inmemory data structures.

Thanks in advance.

Mark


public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.BigData != null)
{
this.BigData.Dispose();
}
}
}
 
Ad

Advertisements

B

Bruce Wood

Mark said:
If your class implements IDisposable, I was told that this increases the
speed with which your class is garbage collected. Is this true?

No, it is not true. IDisposable allows you some control over when
non-memory resources are released: file locks, memory allocated outside
the managed environment, handles to resources in the underlying O/S,
etc. IDisposable has no effect upon when the GC will reclaim memory.

If you have just released a very large memory structure and want to
hasten its collection, you should call GC.Collect(), but even this does
not guarantee immediate cleanup, it just makes it more likely.
 
S

Stoitcho Goutsev \(100\)

Mark,

It is not IDisposable that affects garbage collection it is the type
finalizer (destructor in C#). You can implement IDisposable without having
finalizer, but usually types that implement IDisposable declare finalizers
too just to make sure that the object is disposed even if the programmer
doesn't call Dispose method explicitly.

How finalizers affect GC? I wouldn't say that they slowdown finalization
process; they just need 2 GC cicles in order to be garbage collected. On the
first cicle the finalizer is called and on the second the mempory is marked
as free. Ofcourse they may increase the time needed by the GC because there
is one more finalizer that needs to be ran, but as long as the finalizer
itself doesn't take long time you shouldn't worry about it.

Keep in mind that not all types needs to implement IDisposable. It is
usually implement if the type holds on unmanaged resources that needs to be
cleaned up. If the class holds only managed resource in most of the cases
there is no need of IDisposable and/or finalizers.
 
Ad

Advertisements

D

Dave Sexton

Hi,

I'd just like to add that IDisposable is usually implemented when
IDisposable types are composited, regardless of whether the class itself has
unmanaged resources to be disposed.
 

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