Force a WinForms User Control to unload, removing its delegate event handler from the invocation lis

  • Thread starter Thread starter ewolfman
  • Start date Start date
E

ewolfman

Here's a scenario:

A Business class raises an event, which is handled by a custom WinForms
UserControl. When the control is removed from the containing
Form/Panel, it is not GCed because the Business class retains a pointer
to the event handler delegate in the UserControl.

Is there anyway, except from explicitly removing the delegate from the
Business class' invocation list, to force the UserControl to unload
(i.e. "implicitly" remove the delegate from the invocation list and
make the UserControl eligable for GC)?

Is there a some "best practice" to handle this kind of situation?

In the example below, clicking "button 1" will display "here" in the
Output Window, regardless if "button 2" was clicked or not. The
"dispose" and nullification of the buttonEx1 in button2_click simply
demonstrate that the form no longer references buttonEx1:

// business class
public class BL
{
public event EventHandler Notify;
public void OnNotify()
{
if ( Notify != null)
Notify(this, EventArgs.Empty);
}
}

// custom usercontrol
class ButtonEx : Button
{
public void set(BL b)
{
b.Notify += delegate
{
Debug.WriteLine("here");
};

}
}

// code in form
ButtonEx buttonEx1;
BL b;
public Form1()
{
InitializeComponent();
b = new BL();
buttonEx1 = new ButtonEx();
this.buttonEx1.set(b);
this.panel1.Controls.Add(buttonEx1);
}

private void button1_Click(object sender, EventArgs e)
{
this.b.OnNotify();
}

// this code clears the panel where the custom ButtonEx resides
in
private void button2_Click(object sender, EventArgs e)
{
this.panel1.Controls.Clear();
buttonEx1.Dispose();
buttonEx1 = null;
}

Thanks.
 
Hi

There is no othe way you need to unhook explicitly all events that the
control listens to. I believe the bestpractices would be to do that as soon
as you don't need it anymore. If you can not find a better place to do that
you can put the code in the control's Dispose method. All component's have
Finalizer that calls the Dispose method if form is left for garbage
collecting. I'd suggest reading in MSDN for details on the Dispose design
pattern used throughout the framework.
http://msdn2.microsoft.com/en-us/library/fs2xkftw.aspx
 
Back
Top