事件处理程序的匿名方法不会泄漏? [英] Anonymous method for event handler not a leak?

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

问题描述

无论何时将委托添加到事件处理程序中,都应稍后将其删除,对吧?因此,如果将匿名方法附加到事件,是否会因为以后无法删除它而导致事件处理程序泄漏?此代码示例来自 http://msdn.microsoft.com/en-us/library/0yw3tz5k%28VS.80%29.aspx 似乎暗示这是可以的做法.

Whenever you add a delegate to an event handler, you should remove it later, right? So if you attach an anonymous method to an event, does this create an event handler leak since you can't later remove it? This code sample from http://msdn.microsoft.com/en-us/library/0yw3tz5k%28VS.80%29.aspx seems to imply that this an okay practice though.

// Create a handler for a click event
button1.Click += delegate(System.Object o, System.EventArgs e)
                   { System.Windows.Forms.MessageBox.Show("Click!"); };

这真的可以吗?

推荐答案

无论何时将委托添加到事件处理程序中,都应该稍后将其删除,对吧?

Whenever you add a delegate to an event handler, you should remove it later, right?

不一定,不是.通常,您希望事件处理程序在事件本身可以引发之前一直保持有效-这在UI中当然很常见.

Not necessarily, no. Often you want the event handler to stay valid for as long as the event itself can be raised - that's certainly very common with UIs.

这真的可以吗?

当然,只要您不需要解钩处理程序即可.考虑一下您将钩住事件处理程序的时间.如果是表单(或按钮或其他任何东西)对于垃圾收集而言是可辨认的",那么除去处理程序有什么好处?只是用表单将其作为垃圾收集...

Absolutely, so long as you don't need to unhook the handler. Think about the point at which you'd unhook the event handler. If it's "when the form (or button, or whatever) is elegible for garbage collection" then what benefit is there in removing the handler? Just let it be garbage collected with the form...

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

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