Dispose not getting called

  • Thread starter Thread starter Sunit Joshi
  • Start date Start date
S

Sunit Joshi

Hello All
I have an abstract class C1 with this:

public abstract class C1
{
protected bool m_Dirty;
protected override void Dispose(bool disposing)
{
if(m_Dirty)
WriteOuput();
base.Dispose (disposing);
}

protected void finalize()
{
Dispose(false);
GC.SuppressFinalize(this);
}
public abstract void WriteOuput();
}

Then I have a derived class C2 with this:

public class C2: C1
{
public override void WriteOuput()
{
if(m_Dirty)
{
try
{
m_Log.WriteXml(m_InitialData);
}
catch
{
//Ignore error if file is not valid
}
m_Dirty = false;
}
}
}

I use C2 in my code, but I don't see the parent dispose being called
since the output is never written...Am'I missing something here..??

thanks
Sunit
(e-mail address removed)
 
As previously noted, you should use C++ destructor syntax for your finalize
method in C#:
protected ~C1() // note: I don't think that it matters that it's protected
vs. public.

Also, I think that your call to GC.SuppressFinalize() may be in the wrong
place. You don't want it in the finalize method -- if the finalizer is
running, it means that the GC has already called suppress finalize anyway.

Instead, put the call to suppress finalize in the public version of the
Dispose method, so that if the calling code calls dispose manually, the C1
class will not have its destructor called (no need).

For a more detailed discussion, read this:
http://msdn.microsoft.com/library/d...guide/html/cpconImplementingDisposeMethod.asp
 
Hi,

In addition to the other comments in this thread your
abstract class must descend from the IDisposable
interface. The "Dispose Pattern" is documented in MSDN.

In the Dispose pattern your abstract {or base} class
should take a form like the code below. Descenders of
your abstract class can override the protected virtual
form of the Dispose method to add custom cleanup code.

class MyClass: IDisposable
{
public MyClass()
{
}

~MyClass()
{
Dispose(false);
}

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

protected virtual void Dispose(bool disposing)
{
<<implement cleanup logic here>>
}
}


--Richard
 
Back
Top