匿名事件处理程序和处理 [英] Anonymous event handlers and disposing

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

问题描述

我对匿名事件处理程序相当短的问题:



这是我所的代码:

 公共无效AddTestControl(控制CTRL)
{
ctrl.Disposed + =(O,E)=> {RemoveTestControl(CTRL); };
ctrl.SomeEvent + = _Control_SomeEvent;
}

公共无效RemoveTestControl(控制CTRL)
{
ctrl.SomeEvent - = _Control_SomeEvent;
}



时高于精细这段代码,还是应该代码,以消除被改写已出售事件处理程序?
事情是这样的:

 公共无效AddTestControl(控制CTRL)
{
Ctrl键。处置+ = _Control_Disposed;
ctrl.SomeEvent + = _Control_SomeEvent;
}

公共无效RemoveTestControl(控制CTRL)
{
ctrl.Disposed - = _Control_Disposed;
ctrl.SomeEvent - = _Control_SomeEvent;
}


解决方案

一般情况下,唯一的情况下您需要删除从对象的事件处理程序,以便它是符合垃圾收集时的发布者的对象(一个定义事件)生活比的用户对象(包含事件处理的)。在这种情况下,GC将不能够当它超出范围,因为它仍然正在由发布者引用以释放订户



在此情况下,假设这是的WebForms或WinForms的,发布者(也就是控制对象),最有可能是的子对象的用户的(可能是表格),这将是第一个走出去的范围内采取所有相关的对象吧。因此,有无需移除事件处理程序


I have a rather short question about anonymous event handlers:

This is the code that I have:

public void AddTestControl(Control ctrl)
{
    ctrl.Disposed += (o, e) => { RemoveTestControl(ctrl); };
    ctrl.SomeEvent += _Control_SomeEvent;
}

public void RemoveTestControl(Control ctrl)
{
    ctrl.SomeEvent -= _Control_SomeEvent;
}

Is this code above fine, or should the code be rewritten in order to remove the Disposed Event Handler? Something like this:

public void AddTestControl(Control ctrl)
{
    ctrl.Disposed += _Control_Disposed;
    ctrl.SomeEvent += _Control_SomeEvent;
}

public void RemoveTestControl(Control ctrl)
{
    ctrl.Disposed -= _Control_Disposed;
    ctrl.SomeEvent -= _Control_SomeEvent;
}

解决方案

Generally, the only situation where you need to remove the event handlers from an object in order for it to be eligible for garbage collection is when the publisher object (the one defining the event) lives longer than the subscriber object (the one containing the event handlers). In such a situation the GC won't be able to release the subscriber when it goes out of scope since it's still being referenced by the publisher.

In this case, assuming this is WebForms or WinForms, the publisher (that is the Control object), is most likely a child object of the subscriber (probably a Page or a Form), which will be the first to go out of scope taking all its associated objects with it. Hence there's no need to remove the event handlers.

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

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