处理它引用的对象后,事件会发生什么?
如果我将某个对象的方法链接到委托,然后处理该对象,会发生什么?
像这样:
class Hunter
{
public event Action Shoot;
public execute()
{
Form formBabySeal = new Form();
Shoot += formBabySeal.Close;
formBabySeal.Show();
formBabySeal.Close(); //Dispose Form
if (Shoot != null)
{
Shoot(); //event is null?
}
}
}
what happens if i link a method of some object to a delegate, and then dispose of the object?
Like this:
class Hunter
{
public event Action Shoot;
public execute()
{
Form formBabySeal = new Form();
Shoot += formBabySeal.Close;
formBabySeal.Show();
formBabySeal.Close(); //Dispose Form
if (Shoot != null)
{
Shoot(); //event is null?
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
formBabySeal
不只是因为您处置它而null
。因此,formBabySeal.Close()
将被调用。当查看调用的方法时,您的代码与此等效:
这将关闭表单(第一次调用
Close
),第二次调用不会执行任何操作,因为表单已经关闭。然而,正如 Steve 在评论部分指出的那样,您的代码将引入内存泄漏,因为
Shoot
仍然保留对formBabySeal
Close 方法的引用因此,只要Hunter
类的实例处于活动状态,formBabySeal
就会保持活动状态。formBabySeal
is notnull
just because you dispose it. So,formBabySeal.Close()
will be called.Your code is equivalent to this when looking at what methods are called:
This will close the form (first call to
Close
) and the second call won't do anything, because the form is already closed.However, as Steve points out in the comment section, your code will introduce a memory leak, because
Shoot
still holds a reference to theClose
method offormBabySeal
and because of thisformBabySeal
will be kept alive as long as the instance of the classHunter
is alive.带有 SOS 扩展的 WinDBG 有一种方法可以显示任何对象的 GCRoot。这可能会给你更多线索。
WinDBG with SOS extensions has a way to show GCRoot of any object. This might give you more clues.