I have a form with a panel on which I dynamically load multiple user controls. I handle events for each of these controls.
UserControl userControl1 = LoadControl("control.ascx") as UserControl;
userControl1.Event += new ControlEventHandler(userControl_Event);
this.Panel.Controls.Add(userControl1);
UserControl userControl2 = LoadControl("control.ascx") as UserControl;
userControl2.Event += new ControlEventHandler(userControl_Event);
this.Panel.Controls.Add(userControl2);
...
Now when I get rid of the controls on the Panel, I simply do a
this.Panel.Controls.Clear();
Does the Clear() function take care of getting rid of the events or should I be doing
foreach(Control control in this.Panel.Controls)
{
UserControl userControl = control as UserControl;
if(userControl != null)
{
userControl -= userControl_Event;
}
}
before I Clear() the content of the Panel?
Basically, i'm looking for a way to load user controls dynamically and handle their events without creating a leak when I get rid of them.
Thanks!
EDIT: Because my controls are created in the Page_Init event of the page (each time, as they are loaded dynamically), is it correct to say that their lifespan cannot be longer than the page's lifespan? From what I understand, the control doesn't exist after a post back. A new one is created each time. Therefore, I shouldn't have to unregister the event because the object it doesn't even exist on the next page load. Is that correct?
The page will hold references to the dynamically instantiated controls even after the collection has been cleared, which will prevent the controls from being collected until the page is itself collected.
In this particular situation this will work out fine because the life of the page is very short.
However, if this were instead a windows forms app, then the memory would effectively be leaked until the form was released.
In general it is a good idea to unsubscribe your events when you release the objects that the events go to, as this is the source of the vast majority of .net memory leaks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With