views:

504

answers:

3

Sorry if I'm missing something obvious, but I'm trying to clear the controls (a series of user controls) from a FlowLayoutPanel - (panelName).Controls.Clear();. Unfortunately this doesn't seem to be calling the destructors for the objects on the panel - the User Objects column in the task manager just keeps going up and up, until it hits 10,000 and throws an excecption.

Does anyone know what I'm missing here?

+1  A: 

.NET does not have the concept of destructors. .NET has something called "finalizers" which look syntactically like destructors in C#. For more information, check out Jeff Richter's awesome book on how the CLR works -- CLR via C#.

You may want the objects to implement the IDisposable pattern, and then call their Dispose() method when you're done with them.

Dave Markle
Sorry, brain not in gear on the language, I meant finalizers I promise :-)Either way, it's not getting called. The custom control implements IDisposable, which does all it's supposed to. I've tried with a finalizer in case, also destroying the children. I've tried explicitly calling the garbage collector - in all cases, user objects just marches up to 10k and throws an exception.
eftpotrm
What's the exception? From what you say, I don't think you fully understand the mechanisms of finalizers and the IDisposable interface...
Dave Markle
Very possibly - error creating window handle.
eftpotrm
+1  A: 

Not a solution, but a workaround - the objects do seem to be destroyed by this (rough, from memory) code:

while(FlowLayoutPanel.Controls.Count > 0)
     FlowLayoutPanel.Controls.Remove(0);
eftpotrm
A slight variation is:while(FlowLayoutPanel.Controls.Count > 0){ FlowLayoutPanel.Controls.Clear();}
John M
Good point, that would be faster wouldn't it :)
eftpotrm
A: 

Try using a memory profiler, (e.g. ants) it will tell you what is keeping the control alive. Trying to 2nd guess this type of problem is very hard.

Red-gate gives 14 days tail that should be more then enough time to tack down this problem and decide if a memory profiler provides you with long term value.

There are lots of other memory profilers on the market (e.g. .NET Memory Profiler) most of them have free tails, however I have found that the Red-Gate tools are easy to use, so tend try them first.

Ian Ringrose