Our application adds and removes from this main window UserControls WPF (4.0), and we noticed that they do not receive garbage collection (through WeakReferences, which never returns null). It seems that if UserControl has a binding, this happens even if the control has not been added to the tree. Simplest playback in console application :
Main program
class Program { [STAThread] static void Main(string[] args) { var obj = GetObj(); var ctl = GetCtl(); for (int x = 0; x < 4; x++) { GC.Collect(); Thread.Sleep(1000); } bool objAlive = obj.IsAlive; bool ctlAlive = ctl.IsAlive; Console.WriteLine(objAlive + "-" + ctlAlive); Console.ReadLine(); } private static WeakReference GetObj() { return new WeakReference(new object()); } private static WeakReference GetCtl() { return new WeakReference(new MyCtl()); } }
MyCtl User Control (The code behind is standard and has not been changed
<UserControl <!--Snip Default Namespaces-->> <TextBlock Text="{Binding Blah}" /> </UserControl>
objAlive is false, but ctlAlive is true. If Binding is removed from the UserControl XAML, both values โโare false. If I plug in the memory profiler, MyCtl is still hanging around, but I cannot figure out what is referencing it (tips on how to find this using jetBrains are appreciated).
Is this the expected behavior or do I need to do more to clear my UserFontrols WPF?
source share