事件处理器和C#类析构函数/处置 [英] EventHandlers and C# Classes destructor/Dispose

查看:116
本文介绍了事件处理器和C#类析构函数/处置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑的C#类及其解构。



我要消耗一个类实例的几个事件处理程序我得到在构造

 公共美孚(IFooHandler处理)
{
handler.Load + =负荷;
handler.Close + =关闭;
}



我需要在Foo类被破坏退订该事件。我是否落实的IDisposable ,并在那里退订,或在一个解构?我需要消耗这些事件,我不能这样做的另一种方式。



有关的类之一,我创建了一个实例,检查进度,然后类实例超出范围。而另一个则留在的MainForm ,直到窗体关闭。首先是我很担心,因为它可能还是要该事件处理函数的引用,不能正确去了。



我不想泄漏​​内存。当我应该怎么退订?


解决方案

不这样做在析构函数,因为它不会被调用,而事件处理程序连接:当您安装美孚的一个实例方法,作为律师的事件的处理程序,酒吧将举行至富的引用,所以富不会被垃圾收集,它的析构函数不会被调用

您应该实现IDisposable,和处置你的对象明确

 公共无效的Dispose ()
{
如果(处理!= NULL)
{
handler.Load - =负荷;
handler.Close - =关闭;
}
}


I'm a bit confused about C# Classes and their deconstructor.

I have to consume a few event handlers in a class instance I'm getting in the constructor:

 public Foo(IFooHandler handler)
 {
     handler.Load += Load;
     handler.Close += Close;
 }

I need to unsubscribe to that event when the Foo class is destroyed. Do I implement IDisposable and unsubscribe in there, or in a deconstructor? I need to consume those events, I can't do it another way.

For one of the classes, I create an instance, check progress, and then the class instance goes out of scope. For another it stays in the MainForm until the form is closed. The first is what I'm worried about because it may still have a reference to that event handler and not properly go.

I don't want to leak memory. When and how should I unsubscribe?

解决方案

Don't do it in the destructor, because it won't be called while the event handlers are attached : when you attach an instance method of Foo as a handler for an event of Bar, Bar will hold a reference to Foo, so Foo won't be garbage collected, and its destructor won't be called.

You should implement IDisposable, and dispose your object explicitly

public void Dispose()
{
    if (handler != null)
    {
        handler.Load -= Load;
        handler.Close -= Close;
    }
}

这篇关于事件处理器和C#类析构函数/处置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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