Question Help with memory leak.

tonywilliams

Member
Joined
Feb 12, 2007
Messages
9
Programming Experience
3-5
Hi

I am having a nightmare with a memory leak, I think I know where it occurs, but not to sure how to prevent it.

I have a "diary" system, which shows a day at a time on a "page". Each day/page has up to 12 "panels" containining the information for each appointment. Each of these panels has a right click menu and tooltips as well. It works well, when the user clicks on a date in the calender or the "next day" & "previous day" buttons, it shows the next day with the appointments / panels for that day.

When the user clicks onto the new day the program runs a subroutine which loads the new panels onto the diary page. However at each diary click the memory usage is increased until eventually the program slows down and eventually closes.

Each of the 12 "panels" is a panel that sits in a flowlayout box, the panel has a variety of labels and also the rightclick menu and tooltips. I am certain that this is where the problem lies, as with each click, the new panels are created but the old ones and all attached controls are not disposed properly, as I am not sure where, or how to do this.

Any help would be appreciated.

Regards

Tony
 
When you remove the old control call Dispose method, you only need to do this for the 'top' control that contains the other controls, controls contained by it is automatically disposed.
If you do something like container.Controls.Clear you can use the ControlRemoved event for that container and just do e.Control.Dispose() to have each removed control disposed.

Disposing a control cleans up its resources properly and makes it eligible for garbage collection, if there are no references to the object when that happens.
If you 'forget' to dispose, and there are no references to the object, it will still be garbage collected, only it will take a lot longer time.

About references, a variable that refer to the object is a reference, if that variable is long lived such as being a module level variable you need to set it to Nothing to dereference the object. That the object belongs to a collection also counts as a reference, so removing it from the collection will remove that reference. Further, if you have added event handlers dynamically using the AddHandler statement that is also a reference that will prevent the object from being garbage collected, so you have to use RemoveHandler statement to release those references also.
 
Back
Top