469,892 Members | 2,145 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,892 developers. It's quick & easy.

*Dependent* Unmanaged Resources, Dispose and finalizers

Hi People,

Consider the following:

class A : IDisposable
{
public A ( Stream aResource ) { mResource = aResource ; }

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

protected virtual void Dispose( bool aDisposing )
{
if ( aDisposing )
{
mResource.Dispose();
}
mDisposed = true ;
}

~A() { Dispose(false); }

bool mDisposed = false ;
Stream mResource = null ;
}

AFAICT I can only call mResource.Dispose() in the "Disposing" branch.
That means that for this particular class, its finalizer won't (and can't)
do anything.
So, is it correct to say that this class needs Dispose but not the
finalizer?
Or more generally, are the following guidelines correct?

* Implement a finalizer if the class itself has unmanaged resources
* Implement Dispose if the class OR ANY DEPENDENT OBJECTS has unmanaged
resources.
* Use the Dispose pattern ONLY if you need to implement BOTH (don't use it
if you just need Dispose)

If the above is correct, the following is the correct implementation for
Dispose in this class:

class A : IDisposable
{
public A ( Stream aResource ) { mResource = aResource ; }

public void Dispose()
{
if ( !mDisposed )
{
mResource.Dispose();
mDisposed = true ;
}
}

bool mDisposed = false ;
Stream mResource = null ;
}
Some readers may not know this but finalizers are expensive (their force the
object to live up to the last GC generation and even then are totally free
only after an _additonal_ GC collection). You don't want to add one unless
strictly required.
TIA

Fernando Cacciola
Nov 17 '05 #1
0 1092

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by Mark Broadbent | last post: by
5 posts views Thread by Barry Anderberg | last post: by
4 posts views Thread by Rachel Suddeth | last post: by
156 posts views Thread by Dennis | last post: by
4 posts views Thread by PromisedOyster | last post: by
1 post views Thread by Waqarahmed | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.