In the Dispose(bool) method implementation, Shouldn't one set members to null?

后端 未结 3 693
一个人的身影
一个人的身影 2021-01-14 00:46

None of the guides/notes/articles that discuss IDisposable pattern suggest that one should set the internal members to null in the Dispose(bo

3条回答
  •  -上瘾入骨i
    2021-01-14 01:21

    Releasing any additional references during Dispose is certainly something I try to do, for two reasons:

    • it allows the inner objects to be garbage collected even if the disposed object is still in scope
    • if the inner objects are disposable, it means we only dispose them once even if Dispose() is called repeatedly on the outer object

    For example, I tend to use things like:

    if(someDisposableObject != null)
    {
        someDisposableObject.Dispose();
        someDisposableObject = null;
    }
    (for non-disposable, just set to null)
    someNonDisposableObject = null; // etc
    

    You might also want to set any events to null:

    someEventHandler = null;
    

    This can help minimise the impact if the caller can't fully release their reference (or simply forgets) at the moment. While you should try to release the outer object (for GC), it is relatively easy to accidentally extend the life of the object, for example via a captured variable (anonymous method/lambda), an event, etc.

    If you have a finalizer, then during the GC process there is no benefit doing this, and you shouldn't really call methods on external objects (even Dispose()) - so in short: don't do any of this during a GC sweep.

提交回复
热议问题