2

I have following code:

private void someButton_Click(object sender, EventArgs e)
{
    SomeForm f = new SomeForm();
    this.SomeEvt += f.someFunc;
    this.AnotherEvt += f.anotherFunc;
    f.Show();
}

Should I unregister f.someFunc from this.SomeEvt and f.anotherFunc from this.AnotherEvt?

I don't want to perform neither f.anotherFunc nor someFunc when f is closed

And if I should do unregister, then how would I do that because there no longer SomeForm f after ending of this function?

I'm using .Net framework 4.0 and WinForms.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Krigga
  • 113
  • 10

1 Answers1

4

According to your answer to my comment:

...I don't want to perform f.anotherFunc when f is closed

you should unregister the event, e.g. with lambda:

private void someButton_Click(object sender, EventArgs e)
{
    SomeForm f = new SomeForm();
    this.SomeEvt += f.someFunc;
    this.AnotherEvt += f.anotherFunc;

    f.FormClosed += (ss, ee) => {
      this.SomeEvt -= f.someFunc;
      this.AnotherEvt -= f.anotherFunc;
    };

    f.Show();
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • I never realised the irony in registering an event to unregister another event before seeing it written in a lambda... – Marwie Jul 27 '16 at 13:26
  • @Marwie: there's an irony in the very basic termine *callback function* – Dmitry Bychenko Jul 27 '16 at 13:31
  • Given that `this` is not passed to `f.Show()`, is there a risk of `SomeForm` being closed well after the form with the `someButton_Click` event? In this case wouldn't the reference from `SomeForm` back to `this` form cause the garbage collector to fail to collect `this` form? – Martin Brown Jul 27 '16 at 13:37
  • @Martin Brown: you're quite right, if `MainForm` (let name `this` like that) is closed it could not be collected by GC until `SomeForm` (`f`) has been closed. I don't think this delay being *that* critical; in case if *it is*, one can add one lambda more: `this.FormClosed += (ss, ee) => f.Close();` – Dmitry Bychenko Jul 27 '16 at 13:44