如何在没有代码递归的情况下实现Dispose for IDisposable?

时间:2014-06-18 16:00:18

标签: c# garbage-collection resharper dispose idisposable

我正在重构一些代码,在其上释放Resharper,并且遇到了这个:

public virtual void Dispose()
{
    this.Dispose();
}

...哪个R#标记为“函数在所有路径上递归”可能存在问题

哪个有意义;但是,“官方”(straight from the horse's mouth)代码有点类似(Dispose调用Dispose):

public void Dispose()
{
    Dispose(true);
    // This object will be cleaned up by the Dispose method. 
    // Therefore, you should call GC.SupressFinalize to 
    // take this object off the finalization queue 
    // and prevent finalization code for this object 
    // from executing a second time.
    GC.SuppressFinalize(this);
}

......那些代码甚至不会编译;我得到了,“没有方法的重载'Dispose'需要'1'参数”

那么我怎样才能实现Dispose()而不是递归呢?

更新

如果我尝试这个(来自here):

try
{
    Dispose(true); //true: safe to free managed resources
}
finally
{
    base.Dispose();
}

...我明白了,“'对象'不包含'Dispose'的定义”和“没有方法重载'Dispose'需要'1'参数”

1 个答案:

答案 0 :(得分:1)

看起来你需要正确实现Dispose Pattern:

public class MyThingWithResources : IDisposable
{
    ~MyTHingWithResources()
    {
        // This is a finalizer and is an optional part.
        // Finalizers are not generally required, and are 
        // intended for clearing up unmanaged resources
        // that your class might hold

        // Finalizers are called by the garbage collector
        // So you can never be sure when they are going to
        // be called.

        this.Dispose(false);
    }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // if disposing is true, then the method 
            // is being called as part of a managed disposal
            // this means it should be safe to dispose of managed 
            // resources (.Net classes such as System.IO.Stream )
        }

        // If disposing is false, the Dispose method was called 
        // from the finaliser, so you're in the last chance saloon 
        // as far as tidying stuff up is concerned.
        // Only unmanaged resources (and the objects that wrap them)
        // should be tidied up in this scenario
    }
}