Dave Gordon
Dave Gordon

Reputation: 1835

Does not removing event Handlers cause problems in .Net?

I have the following code:

public void LoadPage()
        {
            LayoutPanel.Controls.Clear();
            ContentObjects = LoadContentObjects();
            foreach (string img in ContentObjects)
            {
                thumbnail = new ctrlThumbnailControl(img);
                LayoutPanel.Controls.Add(thumbnail);
                thumbnail.ThumbnailSelected += Thumbnail_ThumbnailSelected;
            }
        }

        private void Thumbnail_ThumbnailSelected(string PathToMedia)
        {
            lblFileName.Text = PathToMedia;
        }

I create a thumbnail control for each image loaded (limited to 150 per page). The thumbnail controller has an event which is raised on hovering over the control.

So this page has 150 controls with events. When I load the next page I do not remove the events. I do remove the controls. And create another 150 controls adding events to them.

So the question is:

  1. Are the event handlers removed when the controls are Clear()ed?

if not how would I programmatically clear the event handlers without going through each control individually and removing it's handler?

Upvotes: 1

Views: 218

Answers (2)

adv12
adv12

Reputation: 8551

What you're doing is safe because the thing you're throwing away is the thing that holds the reference. That is, each Control is holding a reference to a delegate which holds a reference to the object with the event handler, which is typically a Form or some other long-lived object, but the object with the event handler holds no reference to the Control after it is removed from the UI. The Control becomes completely unreachable (assuming you're not holding a reference to it for some other purpose), so it's irrelevant that it still "knows" about the long-lived object. When the garbage collector runs, the Control will vanish and the delegate with it.

On the other hand, what you don't want to do is register a short-lived object as an event handler for a long-lived object (without remembering to unregister). When you do this, even after you think you've "removed" the short-lived object, the long-lived object still knows about the short-lived object, which keeps it alive such that it is never garbage collected and you have what is essentially a managed-memory version of a memory leak (not to mention that the now-supposedly-disconnected objects will still be responding to events).

Upvotes: 6

mybirthname
mybirthname

Reputation: 18127

If the controls are not visible there is no way to trigger the event from the GUI. There is no need to detach the events. They do not do any "harm".

Upvotes: 1

Related Questions