I have a method I am using to show child windows in my application. For each child window, it sets up a recipient to respond to Close messages from that window. Here is the code:
protected void ShowWpfWindow(Window wpfWindow)
var dc = wpfWindow.DataContext as ChildWindowViewModel;
if (dc == null)
throw new ArgumentOutOfRangeException();
Action<CloseWindowMessage> action = (x) =>
Messenger.Default.Register(wpfWindow, dc, action);
wpfWindow.Owner = MainWindow.Single;
wpfWindow.ShowInTaskbar = false;
The problem is that the
is being garbage collected - I assume this is because it's a local variable to the calling method and the messenger doesn't hold a strong reference to it. This means that once the method is finished, the action is
liable for garbage collecting.
What sort of pattern should I use to avoid this issue? This is actually a bit annoying as I quite like defining my application behavior with little anonymous functions, so perhaps I should change the implementation of
? Or do you think it's a bad idea to define actions like this?
I've gone into some more detail about the problem in my stackoverflow question:
mvvm light message recipient action being garbage collected
I would appreciate any comments you might have.