Purpose of Dispose calling Dispose(IsDisposing) pattern in C#?

巧了我就是萌 提交于 2019-11-27 16:44:14

问题


Here is code from MSDN. I don't understand why the work isn't just done in the regular Dispose() method here. What is the purpose of having the Dispose(bool) method? Who would ever call Dispose(false) here?

public void Dispose() 
{
    Dispose(true);

    // Use SupressFinalize in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize(this);      
}

protected virtual void Dispose(bool disposing)
{
    // If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    if (!_disposed)
    {
        if (disposing) {
            if (_resource != null)
                _resource.Dispose();
                Console.WriteLine("Object disposed.");
        }

        // Indicate that the instance has been disposed.
        _resource = null;
        _disposed = true;   
    }
}

回答1:


The finalizer would call Dispose(false) - in which case you don't touch any of the other managed resources (which may already have been finalized).

Personally I don't follow this pattern often - because I only very, very rarely need a finalizer, and it's also rare for me to write a non-sealed IDisposable implementation. If you're writing a sealed class without a finalizer, I would go for a simple implementation.




回答2:


This is to allow the finalizer to work property, as well as to allow subclasses which derive from your class to dispose properly.

If you want more detailed info, I wrote a 5 part blog series on IDisposable, and covered the subclassing issue in detail in the Subclass from an IDisposable Class article.




回答3:


Regarding the answer,

Your Dispose(disposing) method shouldn't explicitly free resources if it is called from finalizer, since these resources can be already freed by GC.

It's missing an important word. This should really say:

Your Dispose(disposing) method shouldn't explicitly free finalizable (i.e. managed) resources if it is called from finalizer, since these resources can be already freed by GC. Only native resources should be released in a Finalizer.

I'm pretty sure that the poster meant this but just wasn't explicit enough in the post : )




回答4:


Your Dispose(disposing) method shouldn't explicitly free resources if it is called from finalizer, since these resources can be already freed by GC.

So, Dispose(disposing) should check whether it was called manually or from GC and acts appopriately.



来源:https://stackoverflow.com/questions/1579199/purpose-of-dispose-calling-disposeisdisposing-pattern-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!