关闭/处置时,表单必须删除所有事件处理程序吗?

时间:2018-03-27 22:31:02

标签: c# .net events

我偶然发现了这个代码段How to remove all event handlers from a control

void OnFormClosing(object sender, FormClosingEventArgs e)
{
    foreach(Delegate d in FindClicked.GetInvocationList())
    {
        FindClicked -= (FindClickedHandler)d;
    }
}

我的问题是:假设表单即将被处理(在关闭之后),代码片段是必需的还是FindClicked并且所有对事件处理程序委托的引用都只是简单地下载表单GC'ed(引用的事件处理程序不应该导致任何问题)?

1 个答案:

答案 0 :(得分:1)

文档建议您在处置时删除所有事件处理程序:

  

In order to prevent resource leaks, you should unsubscribe from events before you dispose of a subscriber object.

您还可以查看其他可能有用的答案:Does `Control.Dispose()` remove all event registrations?