Reputation: 3968
I use a for loop to generate some controls. Each control presents a special visualisation. I can not use controls like ListBox or somethink like that. I must use my approach. The generated controls are hosted in a Canvas. After a while, some controls are not longer needed. Some controls must be removed. I can manually remove a controls via
c.Children.Remove( ... );
this line. How do I determine that the controls was really collected from be garbage collection? Maybe the control already exists in the memory ... . How do I ensure this?
The problem is that I generate data in tons!
Thanks in advance! :-)
Upvotes: 4
Views: 8035
Reputation: 96702
As long as nothing holds a reference to a control, the garbage collector will get rid of it and you have nothing to worry about. Usually, removing a control from the collection that contains it all you need to do.
But you must be careful with event handlers. If object A subscribes to an event that object B raises, object B holds a reference to object A. If your controls subscribe to, say, Canvas.IsEnabledChanged
, you can remove them from the Canvas
, but the Canvas
will still hold a reference to them so that it can notify them when IsEnabled
changes, and they won't be garbage-collected. This is the most common cause of "memory leaks" in .NET applications. (They're not really memory leaks, but they might as well be.)
Upvotes: 1
Reputation: 31847
Depending on the control that you're using maybe you need to call Control.Dispose()
to free all resources. Be careful is you are using unmanaged resources (Learn more)
I think this is not your case.
Then the garbage collector will collect the object for you.
Also, this article about how Garbage Collector works could be very interesting:
http://www.codeproject.com/KB/dotnet/Memory_Leak_Detection.aspx
Upvotes: 4
Reputation: 12092
if you're sure the objects arent referenced anywhere anymore, you can force a call to the garbage collector with gc.Collect()
Upvotes: 1
Reputation: 35584
You don't really need to. That's the sense of garbage collection: as soon as there are too many dead objects, garbage collection jumps in and cleans them out. Or doesn't clean: the GC knows better what and when to remove.
Upvotes: 2
Reputation: 16025
So if you call to Destroy the control, and you haven't maintained any other references to the control in memory (like in a hashtable of controls or something), then the GC will collect it.
Don't try and force the .NET GC to do something fancy, let it do its work in its own time as the library authors designed it. If you Destroy
it, it will be gone, in due time.
Lastly, if you're concerned that it's still consuming memory, it will be time to start profiling your code, like for instance with RedGate Ants.
Upvotes: 4