Say you have 3 classes that implement IDisposable - A, B and C. Classes A and B are both dependent on class C.
Would it be correct to say that classes A and B's typical implementation of Dispose() would be:
public void Dispose() { if (m_C != null) m_C.Dispose(); }
If there's an instance of A and and instance of B that share the same instance of C, how would you overcome the problem that disposing an instance of A would damage the instance of B?
Last minute addendum - If in point 2 it's a DI container that instantiates all instances, who is responsible for disposing of the objects? Is it the container itself? How?
Thanks, urig
The dispose pattern relies on there being a well-established "owner" who gets to decide when the resource should be disposed of.
If A and B need to refer to the same instance of C, then only one of them should act as "owner".
While you can do what amounts to reference counting, I usually find it's better to just document who "owns" what. For example, when you create a Bitmap
with a stream, from that point on the Bitmap
owns the stream, and you shouldn't dispose it yourself. This can cause a few issues, but it's ultimately simpler than trying to dredge up reference counting.
Doing a null check won't help as if B disposes of C this won't update A's reference.
You have to ensure that only one of the classes has ownership of C. This owner class is then responsible for its disposal.
Generally the class that creates C should be the class that disposes of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With