0

TLDR:

  1. Why Dispose should not be invoked IDisposable members in Finalize() method. (possibly with a null check before) except for performance reasons? (when the members are not shared.)
  2. How can one make sure that IDisposable members free their resources if they should not be disposed in the finalizer and Dispose method wasn't invoked?

From what I have seen, if a class has a field that is IDisposable, then the class should be IDisposable itself. The suggested pattern is:

class MyClass {
    // Some memebers that implement IDisposable interface

    Dispose() 
    {
        Dispose(true);   
        GC.SuppressFinalize();
    }

    Dispose(bool disposed) 
    {
        if(disposed) 
        {
            // Call Dispose on IDesposable members owned by this object
        }

        // Free additional unmnanaged resources if needed
    }

    ~MyClass()
    {
         Dispose(false);
    }
}

The explanation is that during Finalize method, you don't know the state of other managed resources, hence you don't call Dispose on them. However, on the other hand, how can I make sure that other IDisposable members release their resources? The usual suggestion when working IDisposable objects is to wrap them in using statement or in C# 8 put using statement in the beginning of the block, however, if I am not wrong it is not an option when implementing a class.

Progman
  • 16,827
  • 6
  • 33
  • 48
Yuval K
  • 301
  • 2
  • 11
  • 1
    Does this answer your question? [Use of Finalize/Dispose method in C#](https://stackoverflow.com/questions/898828/use-of-finalize-dispose-method-in-c-sharp) Please see the accepted answer – Trevor Feb 16 '20 at 15:51
  • 3
    Those internal members should in turn get garbage collected and then they should handle cleaning up their unmanaged resources. – juharr Feb 16 '20 at 15:51
  • @Çöđěxěŕ Not completely, I think. My question is sort of question on that answer. Let's say I've seen that question before I've asked mine. – Yuval K Feb 16 '20 at 16:00
  • 1
    As a general rule, if your class does not manage unmanaged/native resources (i.e. it on has .NET objects as member data), it should **not** have a finalizer. Finalizers/destructors are hard to write correctly, and result in objects of you type not being able to be garbage collected in Gen0. You need to rely on consumers of you class to properly call you Dispose method – Flydog57 Feb 16 '20 at 19:34

0 Answers0