views:

123

answers:

1

A couple of weeks ago I was having trouble with memory leaks associated with a ContextMenuStrip. That problem was fixed. See that question here

Now I'm having similar issues with ToolStrip controls. As in the previous problem, I'm creating a large number of UserControls and adding them to a FlowLayoutPanel. Each control creates a ToolStrip for itself in its constructor. When a control is removed from the FlowLayoutPanel (the only reference to the control), it seems memory for the ToolStrip is not being released.

However when I comment out the code that creates the ToolStrip the memory leak doesn't happen.

Is this the same sort of issue as the previous one - I need to set the ToolStrip to null? I don't see how that could be since this time the control is creating the strip itself, and all the button events etc are handled inside it. So shouldn't everything be GC'd when the control is no longer referenced?

EDIT: As to the comments, the thing I don't understand is originally I was "making" my own toolstrip out of a panel and some labels. The labels were used as buttons. No memory leaks occurred this way.

The only thing I've changed is using a proper ToolStrip with proper buttons in place of the panel, but all the event handlers are wired the same way. So why is it now leaking memory?

EDIT2: I was just about to post my code but reread the question Dave linked to. It turns out it was the UserPreferenceChangedEvent problem of the ToolStrip. If I set the ToolStrip.Visible property to false, the memory leak doesn't happen!

Now, could I do this in the Dispose method? If so how? I tried copying some code but I get a compile warning: "MyToolStrip.Dispose()' hides inherited member 'System.ComponentModel.Component.Dispose()" I just don't understand the IDisposable interface.

+1  A: 

95% of the time, you're registering event handlers and not unregistering them whenever you clear your controls collection. That would be the first place where I look

(I thought Juliet's comment deserved to be an answer)

Daniel Plaisted
I just added code to make sure all event handlers have been unsubscribed before removing the controls from the FlowLayoutPanel, and memory use is still rising. Unfortunately my trial of Memory Profiler has expired. I just don't know what is going on. I haven't the knowledge to try using IDisposable yet (freaks me out reading about it :). But I don't see why that would be necessary in this case. As I said it worked fine (no memory leak) until I switched to using a ToolStrip, even without unsubscribing from the events.
Dave