I am unit testing my code for memory leaks. If I call Popup.IsOpen = true
, then the garbage collector does not collect the popup or its child. If I comment out Popup.IsOpen = true
, the garbage collector will collect both.
I would like to force garbage collection on the popup so I can properly test my own code.
public void MemoryLeak_Popup()
{
WeakReference weakReferencePopup;
WeakReference weakReferenceChild;
{
Popup popup = new Popup();
popup.Child = new StackPanel();
popup.IsOpen = true;
popup.IsOpen = false;
weakReferencePopup = new WeakReference(popup);
weakReferenceChild = new WeakReference(popup.Child);
popup.Child = null;
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.IsFalse(weakReferenceChild.IsAlive, "Memory leak for the popup's child.");
Assert.IsFalse(weakReferencePopup.IsAlive, "Memory leak for the popup.");
}