触发后取消订阅事件

时间:2018-12-20 19:26:52

标签: c# winforms memory-leaks event-handling

我们有一个没有被垃圾收集器处理的对象,我们认为这是由于注册到以后重建的对象的胭脂事件永远不会被注销。

我们创建了一个方法,该方法也可以在返回表单时运行。 (例如,从表格A转到表格B,然后返回表格A。该方法将在返回表格A 上运行)。在这种方法中,我们正在检查是否要从表单B返回。如果要创建该表单的实例,然后在.FormClosed上附加一个事件。

此代码是从我们的一位合作伙伴处提取的,所以我不知道当附加了该事件的上下文为时,他们决定附加.FormClosed事件的原因当它已经关闭时。 (因此将返回A )。

我不知道的是,我如何脱离.FormClosed事件,但仍然保持在那里触发的逻辑?

代码的基础是:

private void Returning(object sender, EventArgs e)
{
    CoreForm frmSomeChildForm = sender as CoreForm

    if (frmSomeChildForm.Name == "frmB") // We are 'returning' from B
    {
        // Do stuff
        frmSomeChildForm.FormClosed += new FormClosedEventHandler(SomeMethod);
    }
}

private void SomeMethod(object sender, FormClosedEventArgs e)
{
    // This was in the comments for the method:
    // Event added to re-position the search panel back to the top by removing
    //the other two panels and adding them back to the form.
    // The code just calls parent methods of DLLs we don't have the source for.
}

由于从表单B返回时基本上调用了Returning方法,所以为什么要在其中附加.FormClosed事件有意义吗?我不能做这样的事吗?

private void Returning(object sender, EventArgs e)
{
    CoreForm frmSomeChildForm = sender as CoreForm

    if (frmSomeChildForm.Name == "frmB") // We are 'returning' from B
    {
        // Do stuff

        SomeMethod();
    }
}

编辑:

因此,Returning在我们从FormClosed()事件返回的表单上被触发。因此,我们要从中返回的表单应该已经关闭。

SomeMethod的目的尚不完全清楚,但似乎与重置几个控件的显示有关。

0 个答案:

没有答案
相关问题