views:

68

answers:

2

I am having a WPF application where when I close a TabItem from TabControl using TabControl.Items.Remove(TabItem) does not free memory used by TabItem. It just makes TabItem invisible and TabItem object still remains in the memory. Is there any way to remove this TabItem object from memory ? Any help would be appreciated.

A: 

You need to cut out an object from its parent completely for it to be garbage collected. That means also the events (-= blah).

Even that done, the object might still be in memory until the next sweep of the GC.

You can force a call of the GC but it's not recommended. http://msdn.microsoft.com/en-us/library/system.gc.aspx

keyle
I have got a UserControl(TextBoxes+Grids+Graphs+events on these) as a TabItem.Content and on this TabiItem there is one close button(CloseImage+click event). So which event(s) am I supposed to cut (TabItem.Content's events OR Click event put on close button)?
Kushal Waikar
I believe the click ones and remove tab item.
keyle
+1  A: 

As far as I know all eventhandlers must be 'detached', also you should release all bindings on your tabItem.

Also If I am not mistaken CommandBindings, KeyGestures can also cause the leak.

Try using CLR Profiler. It has saved me a lot of hours many times, though I haven't used it with WPF. But I'm pretty sure it can handle it.

nomail
nomail
It can handle it. It can at times be pretty hardwork getting the right granularity however. I recommend using it with SOS/WinDbg to get the dump after you've done the repro rather running under the profiler, which can completely kill performance.
dhopton
Another thing that can be done is to call GC.Collect after removing all event handlers etc, and see if the object is collected (just for debug purposes, of course) if it IS collected, you have no leaks, if not - you still haven't freed something
Captain