tags:

views:

501

answers:

4

I am using WPF.

After adding user controls dynamicaaly at runtime, How to Dispose that user control. Because there is no Dispose Method for User Controls. i dont want to wait untill Garbage Collecter runs.

A: 

Is there a reason you don't want to wait for the GC? If you remove the control from it's parent so there's no references to it then the GC will eat it, there's no need to dispose of it manually.

Steven Robbins
+4  A: 

Even if you were able to dispose it, that wouldn't free memory. Dispose isn't about releasing memory - it's about releasing non-memory resources (e.g. GDI handles). I would assume that if the class doesn't implement IDisposable, it doesn't have any non-memory resources to release.

Jon Skeet
A: 

Thanks Steve.

Firstly i add numerous UsrCtr Elements on my Application Frequently. so if they are't removed instanteously, Huge memory will be wasted.

Actually i am using ForEach Loop at several places to iterate all the elements on the Application (WinForm) , so this loop still show the UserCtrs (After removing the UserCtr as chld)

Further more i also pass the refrence of the UserCtrs to several other places in my project through the Custom Defined Events and Delegate. So if add it at one Place on Main Form, still there may be possiblity that Refrence for the User Control Exists some other Place in the Project.

If there's a reference to the control somewhere else, then there's no way the runtime would let you free the memory for it (even if there were some .NET API to do that). That would render those references invalid - the kind of error .NET was invented to prevent.
Michael Burr
You should really read up on how the GC works. There's a big difference between "removed instantaneously" and "only hang around in gen0 or gen1". If you're frequently creating objects which hang around for a *long* time (going to gen2) and then removing all references, that could be bad.
Jon Skeet
+3  A: 

I think your design is flawed. If you still have a reference to something then you shouldn't try to free the memory anyway. Once something is actually no longer alive (no further references to it) it is effectively available memory in that, the next time you need some memory which cannot be supplied without a GC it will become free[1] and available.

Your design is not wasting memory, it is simply churning memory. This in itself may be problematic but it does not waste memory. If your design holds onto references to controls after they are no longer needed that wastes memory, but you cannot 'band-aid' over the problem by 'deleting' them. You need to tackle the root cause of passing these controls all about the place in a manner that makes their life cycle hard to control.

[1] barring finalizers which do not apply here

ShuggyCoUk