I'm unsure whether a child window is able to be garbage-collected in the following scenario.
- User control contains a "show popup" command
- The command creates a child window, and adds an anonymous listener for the "Closed" event.
public partial class MainPage : UserControl
{
public ICommand PopupCommand { get; private set; }
public MainPage()
{
InitializeComponent();
PopupCommand = new DelegateCommand(arg =>
{
var child = new ChildWindow();
child.Closed += (sender, args) =>
{
MessageBox.Show("You closed the window!");
};
child.Show();
});
}
}
Since PopupCommand's delegate still ostensibly contains a reference the the local child variable, will each invocation of PopupCommand leak memory? Or will the garbage collector somehow recognize that it can dispose of child after it has been closed?
Related: detaching anonymous listeners from events in C# and garbage collection
The following test suggests that, no, the scenario does not result in a memory leak.
The reason is suggested in the answer to the (Winforms) post linked to by Jwosty:
In other words, the memory-leak concern is really the other way around -- the event publisher (the
ChildWindowcontrol) holds a reference to the subscriber (theDelegateCommand), but not the other way around. So, once theChildWindowis closed, the garbage collector will free its memory.