Is there any guidance or best practices around who should call Dispose() on disposable objects when they have been passed into another object\'s methods or cons
One thing I decided to do before I knew much about .NET programming, but it still seems a good idea, is have a constructor that accepts an IDisposable also accept a Boolean which says whether ownership of the object is going to be transferred as well. For objects which can exist entirely within the scope of using statements, this generally won't be too important (since the outer object will be disposed within the scope of the Inner object's Using block, there's no need for the outer object to dispose the inner one; indeed, it may be necessary that it not do so). Such semantics can become essential, however, when the outer object will be passed as an interface or base class to code which doesn't know of the inner object's existence. In that case, the inner object is supposed to live until the outer object is destroyed, and thing that knows the inner object is supposed to die when the outer object does is the outer object itself, so the outer object has to be able to destroy the inner one.
Since then, I've had a couple of additional ideas, but haven't tried them. I'd be curious what other people think:
IDisposable object. I haven't really figured out the most natural pattern for doing this, but if an object uses reference counting with Interlocked increment/decrement, and if (1) all code that manipulates the object uses it correctly, and (2) no cyclic references are created using the object, I would expect that it should be possible to have a shared IDisposable object which gets destroyed when the last usage goes bye-bye. Probably what should happen would be that the public class should be a wrapper for a private reference-counted class, and it should support a constructor or factory method which will create a new wrapper for the same base instance (bumping the instance's reference count by one). Or, if the class needs to be cleaned up even when wrappers are abandoned, and if the class has some periodic polling routine, the class could keep a list of WeakReferences to its wrappers and check to ensure that at least some of them still exist.IDisposable object accept a delegate which it will call the first time the object is disposed (an IDisposable object should use Interlocked.Exchange on the isDisposed flag to ensure it's disposed exactly once). That delegate could then take care of disposing any nested objects (possibly with a check to see if anyone else still held them).Does either of those seem like a good pattern?