Events cause memory leaks?

Use this forum for questions on how to use .NET Memory Profiler and how to analyse memory usage.
Post Reply
Posts: 2
Joined: Mon Apr 07, 2008 5:23 pm

Events cause memory leaks?

Post by ajh » Mon Apr 07, 2008 5:27 pm


Hopefully someone can set me straight. I am finding that a large .NET 1.1 application that we are upgrading to .NET 2.0 is using a HUGE amount of memory - specifically, opening and closing a form over and over causes memory consumption to jump every time.

I have started to use the .NET memory profiler, and see that events that are registered in the form seem to be the cause - but I'm not 100% sure.

So my question is, when you register an event handler (e.g. button click), what are the requirements for unregistering? If the event is registered through the designer (InitializeComponent), does that event need to be unregistered in 'Dispose'? If the event is registered in user defined code, does it need to be unregistered in 'Dispose'?


Andreas Suurkuusk
Posts: 1029
Joined: Wed Mar 02, 2005 7:53 pm

Post by Andreas Suurkuusk » Tue Apr 08, 2008 8:05 am

You only need to unregister an event handler if the event source can be expected to have a longer life-time than the event consumer. For instance if the consumer is a control that needs to be notified about an external event, such as SystemEvent.UserPreferencesChanged, then the event handler must be explicitly removed when the control is no longer used (since UserPreferencesChanged is a static producer that survives for the lifetime of the application). But the event handlers that are added in InitializeComponent are usually connecting the child controls with the parent form. Since the lifetime of the form and the controls are normally the same, there's no need to remove those event handlers.

If you manually add event handlers then you need to analyse whether you need to explicitly remove them. Of course, if you know when the event handlers can be removed, it doesn't hurt to always remove them.
Best regards,

Andreas Suurkuusk
SciTech Software AB

Post Reply

Who is online

Users browsing this forum: No registered users and 27 guests