Who should call Dispose on IDisposable objects when passed into another object?

前端 未结 5 1049
孤城傲影
孤城傲影 2020-11-27 15:03

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

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-27 15:43

    In general, once you're dealing with a Disposable object, you're no longer in the ideal world of managed code where lifetime ownership is a moot point. Resultantly, you need to consider what object logically "owns", or is responsible for the lifetime of, your disposable object.

    Generally, in the case of a disposable object that is just passed into a method, I would say no, the method should not dispose the object because it's very rare for one object to assume ownership of another object and then be done with it in the same method. The caller should be responsible for disposal in those cases.

    There is no automatic answer that says "Yes, always dispose" or "No, never dispose" when talking about member data. Rather, you need to think about the objects in each specific case and ask yourself, "Is this object responsible for the lifetime of the disposable object?"

    The rule of thumb is that the object responsible for creating a disposable owns it, and thus is responsible for disposing it later. This doesn't hold if there's an ownership transfer. For example:

    public class Foo
    {
        public MyClass BuildClass()
        {
            var dispObj = new DisposableObj();
            var retVal = new MyClass(dispObj);
            return retVal;
        }
    }
    

    Foo is clearly responsible for creating dispObj, but it's passing the ownership to the instance of MyClass.

提交回复
热议问题