IDisposable的GC.Sup pressFinalize(本)的位置位置、GC、IDisposable、pressFinalize

2023-09-03 02:32:28 作者:薄荷音少年i

我使用的是默认的IDisposable实现模板(模式)对我的code。

片段:

 公共无效的Dispose()
{
    处置(真);

    GC.Sup pressFinalize(本);
}

受保护的虚拟无效的Dispose(布尔isDisposing)
{
    如果(!this.disposed)
    {
        如果(isDisposing)
        {
            //清理托管资源
        }

        //清理非托管资源

        this.disposed = TRUE;
    }
}
 

我的问题:为什么是叫GC.Sup pressFinalize(本),在公众的Dispose方法?我把GC.Sup pressFinalize(本)中的如果(isDisposing)受保护的方法部分,处理后的管理资源。

这样的:

 受保护的虚拟无效的Dispose(布尔isDisposing)
{
    如果(!this.disposed)
    {
       如果(isDisposing)
       {
           //清理托管资源

           GC.Sup pressFinalize(本);
       }

       //清理非托管资源

       this.disposed = TRUE;
    }
}
 

解决方案

我想的模板设计模式的一个明显例子。

英雄联盟S10入围赛LGC vs SUP比赛视频 LGC状态火热击败SUP

您抽象类是设计时考虑的所需的所有重要/必要任务护理(在这里,GC.Sup pressFinalize(本)),并允许派生类重写的code只有一部分。

有2例在这里: 片段1,燮pressFinalize,在处置 片段2,燮pressFinalize,在处置(真)

下面,摘录1,可以确保始终执行GC.Sup pressFinalize。虽然片段2,叶GC.Sup pressFinalize执行摆布派生类

因此​​,通过将GC.Sup pressFinalize,在Dispose方法,你为你的类的设计者将始终确保不论任何code写的派生类,GC.Sup pressFinalize将被执行。

这是写燮pressFinalize的处置而不是废弃的只有利益(真正的)。

I use a default IDisposable implementation template (pattern) for my code.

snippet:

public void Dispose()
{
    Dispose(true);

    GC.SuppressFinalize(this);
}

protected virtual void Dispose(bool isDisposing)
{
    if (!this.disposed)
    {
        if (isDisposing)
        {
            //cleanup managed resources
        }

        //cleanup unmanaged resources

        this.disposed = true;
    }
}

My question: why is the call "GC.SuppressFinalize(this)" in the Dispose public method? I would place "GC.SuppressFinalize(this)" in the "if (isDisposing)" section of the protected method, after disposing managed resources.

Like this:

protected virtual void Dispose(bool isDisposing)
{
    if (!this.disposed)
    {
       if (isDisposing)
       {
           //cleanup managed resources

           GC.SuppressFinalize(this);
       }

       //cleanup unmanaged resources

       this.disposed = true;
    }
}

解决方案

I suppose its a clear case of Template Design pattern.

Your abstract class is Designed to take care of all important/necessary tasks required (Here, GC.SuppressFinalize(this)), and allowing a derived class to override only some part of the code.

There are 2 cases here: Snippet 1, SuppressFinalize, in Dispose Snippet 2, SuppressFinalize, in Dispose(true)

Here, Snippet 1, makes sure that GC.SuppressFinalize is always executed. While snippet 2, leaves the execution of GC.SuppressFinalize at the mercy of derived class.

So, by putting GC.SuppressFinalize, in Dispose method, you as a designer of your class will always make sure that irrespective of whatever code written by derived classes, GC.SuppressFinalize will be executed.

This is only the benefit of writing SuppressFinalize in Dispose rather then Dispose(true).