删除用户控件时处理程序 [英] Remove handler when usercontrol is disposing

查看:99
本文介绍了删除用户控件时处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪一个是正确的?

这一个:

protected override void Dispose(bool disposing)
{
    if (disposing && (components != null))
    {
        this.ctlRBContent1_GetBuildName -= _ctlBottom.GetBuildName;
        components.Dispose();
    }
    base.Dispose(disposing);
}

OR

这一个:

~ ctlRemoteBuildContent1()
{
    this.ctlRBContent1_GetBuildName -= _ctlBottom.GetBuildName;
}

我试图切换这2个功能。当我执行UserControl处理时,它没有跳转到切换行:/

I tried to toggle this 2 functions. When I did UserControl disposing, it didn't jump into the toggle line :/

推荐答案

如果你清理一个析构函数,无法保证析构函数何时运行。具有析构函数的对象也需要更多的工作才能使垃圾回收器处理。因此,最好实现IDisposable,这是您的第一个例子。

If you clean up in a destructor, there's no guarantee as to when the destructor will be run. Objects with a destructor also require more work for the garbage collector to handle. It's preferable therefore to implement IDisposable, which is your first example.

请注意,您的代码段未能完全实现推荐的IDisposable模式。请参阅这篇文章,以获得一个很好而完整的解释:

Note that your code snippet does not fully implement the recommended IDisposable pattern. Please see this article for a good and complete explanation:

http://www.csharphelp.com/2010/02/c-garbage-collecting-destructors-versus-dispose/

在您的代码片段中,如果由于某些原因组件为null,则不会删除事件处理程序。只有组件的空检查才能保护 components.Dispose() call。

In your code snippet, if for some reason components is null, you would not remove the event handler. The null check for components should only be done to protect the components.Dispose() call.

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this.ctlRBContent1_GetBuildName -= _ctlBottom.GetBuildName;
        if (components != null)
        {
            components.Dispose();
        }
    }
    base.Dispose(disposing);
}

这篇关于删除用户控件时处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆