Groups | Blog | Home
all groups > c# > august 2003 >

c# : Dispose pattern improvement?



Jon Skeet
8/5/2003 5:24:27 PM
[quoted text, click to view]

In what way would the associated bool member not be necessary? You'd
still need to check whether or not the object had been disposed for
methods *other* than dispose itself (eg writing to a stream which has
already been disposed).

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet/
Jon Skeet
8/5/2003 5:50:59 PM
[quoted text, click to view]

Ah - sorry, I thought you were suggesting that the bool member in your
example wouldn't be necessary. I wasn't entirely clear about what you
were suggesting...

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet/
Andreas Huber
8/5/2003 6:12:39 PM
Hi there

Is there a reason why .NET framework base classes implementing IDisposable
(like e.g. System.ComponentModel.Component) do not prevent multiple calls to
the protected virtual void Dispose( bool disposing ) function?

Derived classes would then no longer need to check whether they have been
disposed already and the associated bool member wouldn't be necessary
either.

Example code:

class Base : IDisposable
{
private bool disposed = false;

~Base()
{
if ( !this.disposed ) // *** here ***
{
Dispose( false );
this.disposed = true;
}
}

public void Dispose()
{
if ( !this.disposed ) // *** here ***
{
Dispose( true );
GC.SuppressFinalize( this );
this.disposed = true;
}
}

public void SomeMethod()
{
if ( this.Disposed )
{
throw new ObjectDisposedException( "Base" );
}

// ...
}

// This property is necessary so that subclass methods can check whether
// the object has been disposed.
protected bool Disposed
{
get { return this.disposed; }
}

protected virtual void Dispose( bool disposing )
{
if ( disposing )
{
// release my managed resources
}

// release my unmanaged resources
}
}


class Derived : Base
{
public void SomeOtherMethod()
{
if ( this.Disposed )
{
throw new ObjectDisposedException( "Derived" );
}

// ...
}

protected override void Dispose( bool disposing )
{
try
{
if ( disposing )
{
// release my managed resources
}

// release my unmanaged resources
}
finally
{
base.Dispose( disposing );
}
}
}
Andreas Huber
8/5/2003 6:39:38 PM
[quoted text, click to view]

I'm not sure I understand what you mean as that's what the protected
Disposed property in the base class would be for...

I quote from my original message:

[quoted text, click to view]
[snip]

Regards,

Andreas
Andreas Huber
8/5/2003 7:04:55 PM
[quoted text, click to view]

I see, sorry for being unclear...

Regards,

AddThis Social Bookmark Button