C#明确删除事件处理程序 [英] C# Explicitly Removing Event Handlers

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

问题描述

我在想,如果一个对象设置为null将清理附着在物体事件的任何事件处理器...

I was wondering if setting an object to null will clean up any eventhandlers that are attached to the objects events...

例如

Button button = new Button();
button.Click += new EventHandler(Button_Click);
button = null;

button = new Button();
button.Click += new EventHandler(Button_Click);
button = null;



等等...

etc...

请问这个造成内存泄露?

Will this cause a memory leak?

推荐答案

如果有到按钮在任何地方,那么就没有必要在这里删除事件处理程序,以避免内存泄漏。事件处理程序是单向的引用,所以拆卸时,事件的对象是长寿命的他们只需要,并且要避免生活比他们更长的处理的(即处理方法的对象)应该。在你的榜样,这是情况并非如此。

If there are no other references to button anywhere, then there is no need to remove the event handler here to avoid a memory leak. Event handlers are one-way references, so removing them is only needed when the object with events is long-lived, and you want to avoid the handlers (i.e. objects with handler methods) from living longer than they should. In your example, this isn't the case.

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

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