0

I'm unclear about what classes need to implement IDisposable. Obviously those with unmanaged resources, but what about those with member variables that are IDisposable?

For example, if a class has a member variable that's a ManualResetEvent (which is IDisposable), does that class need to implement IDisposable so that it can call that ManualResetEvent's Dispose()?

If that class is IDisposable, its ManualResetEvent member's Dispose will be called when the class' Dispose() is called. However, if an object of that class isn't disposed of properly, its finalizer will call its Dispose(bool disposing) function, but that member's Dispose won't get called (because its a managed object). I assume that whatever unmanaged resources are used by ManualResetEvent are disposed of properly in its IDisposable implementation, even through its finalizer. My confusion, then, is whether there would be any benefit in making my class IDisposable, since I see no data leakage risk. Is the only benefit that unmanaged resources of its IDisposable members will be released a few milliseconds earlier?

Should IDisposable only be implemented in classes that directly hold unmanaged resources, and not in classes that don't directly hold unmanaged resources even if they have members that are themselves IDisposable?

uncaged
  • 597
  • 1
  • 5
  • 17
  • 4
    Does this answer your question? [Should I implement IDisposable when class has IDisposable member but no unmanaged resources?](https://stackoverflow.com/questions/37934420/should-i-implement-idisposable-when-class-has-idisposable-member-but-no-unmanage) –  Mar 17 '20 at 17:33
  • If you're using unmanaged resources you need to implement a finalizer. `IDisposable` alone doesn't cut it as it's not called by the GC. – Zer0 Mar 17 '20 at 17:34
  • Yes, those that have IDisposable fields too. – Ricardo Peres Mar 17 '20 at 17:35
  • Amy: Thank you! The link you gave has a link to an official answer: https://learn.microsoft.com/en-us/visualstudio/code-quality/ca1001-types-that-own-disposable-fields-should-be-disposable – uncaged Mar 17 '20 at 18:15
  • While the dispose pattern ensures that resources are released, there's one aspect that you're missing, they're released at a deterministic time. Especially useful when you have resource intensive tasks and you are done with a particular resource and it would be expensive to have around. And if you can't guarantee when that resource is cleaned up, you can run into problems. – Jeff Mercado Mar 17 '20 at 19:13

0 Answers0