0

First thing: This is a compact framework 3.5 application.

I have a very weird problem. In a Dispose-Method the application disposes items in a collection and after that clears the list. So far nothing special and it works like a charm when Dispose is called by my application. But as soon as the Garbage Collector calls the Finalizer, which calls the same Dispose-Method the system throws a NotSupported-Exception on the Clear-Method of the generic collection.

Here is the body of the Dispose-Method:

public override void Dispose()
{
    if (items != null)
    {
        foreach (Shape item in items)
        {
            item.Dispose();
        }
        items.Clear();
        items = null;
    }
    base.Dispose();
}

I'm totally stuck here. Maybe someone can explain this to me, or had a similar problem and solved it.

  • Why is the finalizer calling a parameterless Dispose? Very very rarely should a Finalizer call Dispose on another object, unless one knows that both (1) the other object's Dispose method will work, usefully, in the context of a finalize thread, and (2) the other object won't adequately care of finalizing itself. Nothing in your code example suggests that even one of those conditions is met. – supercat May 09 '12 at 18:31

1 Answers1

0

A finalizer needs only call Dispose if there are unmanaged resources to clean up. You cannot attempt to access managed resources when being called from the finalizer.

As mentioned in the comment above, there is no reason [that we can see] that your class should implement a finalizer.

For reference, should you need to use a finalizer, the Dispose pattern to use as follows:

// The finalizer
~MyClass()
{
    Dispose(false);
}

// The IDisposable implemenation
public void Dispose()
{
    Dispose(true);
    GC.SuppressFinalize(this);
}

// The "real" dispose method
protected virtual void Dispose(bool disposing)
{
    if (!_disposed)
    {
        if (disposing)
        {
            // Dispose managed objects here
        }
        else
        {
            // Free unmanaged resources here
        }
        _disposed = true;
    }
}
roken
  • 3,946
  • 1
  • 19
  • 32