CA1063 从类中删除终结器并将其添加到 dispose 为 false 的代码中

CA1063 Remove finalizer from class and add it in the code where disposing is false

提问人:RendonLs 提问时间:9/11/2020 更新时间:9/11/2020 访问量:115

问:

我一直在努力避免这个警告,我根据 CA1063 尝试并理解的是:正确实现 IDisposable 是终结器应该只包含 false 中的 Dispose 方法。其余的代码应该写在其他地方。我尝试实现 Microsoft 的示例,但是当我添加 Dispose 方法时,出现一个错误,指出 dispose 方法已经存在,唯一已经存在的 Dispose 在设计器中。是设计师在制造麻烦吗?

~TimerUpdate()
{
    Dispose(false);
    try
    {
        this.matlab = null;
        this.command = null;
    }
    catch(Exception ex)
    {
        Console.WriteLine("Exception in " + this.GetType().Name + ".cs: " + System.Reflection.MethodBase.GetCurrentMethod().Name + "(): " + ex.Message);
        this.Dispose();
    }
}

private void TimerUpdate_FormClosing(object sender, FormClosingEventArgs e)
{
    try
    {
        this.updateRateBox_ValueChanged(sender, e);
        this.updateRateCAN_ValueChanged(sender, e);
        this.matlab = null;
        this.Dispose();
    }
    catch(Exception ex)
    {
        Console.WriteLine("Exception in " + this.GetType().Name + ".cs: " + System.Reflection.MethodBase.GetCurrentMethod().Name + "(): " + ex.Message);
        this.Dispose();
    }
}
C# 互操作 FXCOP

评论

1赞 Matthew Watson 9/11/2020
您需要将 Dispose() 从 designer.cs 文件移动到该类的主代码文件中。如果检查“designer.cs”文件,则可以看到 Dispose() 位于“Windows 窗体设计器生成的代码”部分之外,因此可以安全地移动。每次创建控件/窗体时,我都会将 Dispose() 方法从设计器文件中移出 - 我希望有一个设置,这样我就不必一直自己做!
1赞 RendonLs 9/11/2020
@MatthewWatson好的,完美的,终结器中的代码我应该粘贴到Dispose()中吗?
0赞 Matthew Watson 9/11/2020
是的,终结者应该只调用,不做任何其他事情。但是您需要自己编写方法,然后更改为调用 - 与您发布的链接中的示例代码完全一样。Dispose(false)protected virtual Dispose(bool)Dispose()Dispose(true)
0赞 ndogac 9/11/2020
您的类是否具有本机资源(如句柄)或托管资源(如?如果只有托管资源,则可以覆盖和调用托管资源。在这种情况下,不需要此模式。我说得对吗?@MatthewWatsonIntPtrFileStreamDispose()_resource?.Dispose()
0赞 ndogac 9/11/2020
来自 Microsoft 文档: 注意:如果此类不拥有非托管资源,请完全省略终结器,但保留其他方法的原样。

答: 暂无答案