Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A problematic example of the IDisposable pattern?

Say you have 3 classes that implement IDisposable - A, B and C. Classes A and B are both dependent on class C.

  1. 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();
    }
    
  2. 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?

  3. 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

like image 613
urig Avatar asked Jul 14 '10 10:07

urig


2 Answers

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.

like image 75
Jon Skeet Avatar answered Oct 23 '22 21:10

Jon Skeet


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.

like image 23
Mongus Pong Avatar answered Oct 23 '22 21:10

Mongus Pong