I am going to make a GUI that will have dynamically created sets of controls with events assigned to them. I will need to add and remove those controls at runtime. It will look like this:
FlowLayoutPanel.Controls.Clear();
<< add new controls, assigning Click events with += >>
I have heard that assigning event handlers with += can cause memory leaks (more specificly, memory will not be freed until application has exited). I want to avoid this. I know i can write some functions like here How to remove all event handlers from a control to find all event handlers and remove them but it looks very complex.
Is there another way? Does calling Dispose help remove those event handlers? Can you destroy objects to force their memory to be freed like in C/C++?
Thanks!
PS: Problem is, i dont know what event to detach. I will create lots of labels and add different kinds of onclick events to them. When its time to clean the flow layout panel, there is no way to know what event handler was attached to which label.
This is the example code (_flowLP is a FlowLayoutPanel) - this Refresh() function is ran multiple times before the application exits.
private void Refresh()
{
Label l;
Random rnd = new Random();
// What code should i add here to prevent memory leaks
_flowLP.Controls.Clear();
l = new Label();
l.Text = "1";
if (rnd.Next(3) == 0) l.Click += Method1;
if (rnd.Next(3) == 0) l.Click += Method2;
if (rnd.Next(3) == 0) l.Click += Method3;
_flowLP.Controls.Add(l);
l = new Label();
l.Text = "2";
if (rnd.Next(3) == 0) l.Click += Method1;
if (rnd.Next(3) == 0) l.Click += Method2;
if (rnd.Next(3) == 0) l.Click += Method3;
_flowLP.Controls.Add(l);
l = new Label();
l.Text = "3";
if (rnd.Next(3) == 0) l.Click += Method1;
if (rnd.Next(3) == 0) l.Click += Method2;
if (rnd.Next(3) == 0) l.Click += Method3;
_flowLP.Controls.Add(l);
l = new Label();
l.Text = "4";
if (rnd.Next(3) == 0) l.Click += Method1;
if (rnd.Next(3) == 0) l.Click += Method2;
if (rnd.Next(3) == 0) l.Click += Method3;
_flowLP.Controls.Add(l);
l = new Label();
l.Text = "5";
if (rnd.Next(3) == 0) l.Click += Method1;
if (rnd.Next(3) == 0) l.Click += Method2;
if (rnd.Next(3) == 0) l.Click += Method3;
_flowLP.Controls.Add(l);
l = new Label();
l.Text = "6";
if (rnd.Next(3) == 0) l.Click += Method1;
if (rnd.Next(3) == 0) l.Click += Method2;
if (rnd.Next(3) == 0) l.Click += Method3;
_flowLP.Controls.Add(l);
}