This coding style will lead to a memory leak.

Following the MVVM pattern, I am trying to connect the display of a child window by view in response to a request from a view model.

Using MVVM-Light Messenger, View will register a request to display the child window in the view designer like this:

InitializeComponent(); Messenger.Default.Register<EditorInfo>(this, (editorData) => { ChildWindow editWindow = new EditWindow(); editWindow.Closed += (s, args) => { if (editWindow.DialogResult == true) // Send data back to VM else // Send 'Cancel' back to VM }; editWindow.Show(); }); 

Does the ChildWindow Closed event subscribe using the Lambda garbage collection problem. Or in another way, when (if ever), editWindow will become unreferenced and therefore a candidate for garbage collection.

+6
c # event-handling silverlight mvvm-light
source share
1 answer

editWindow will contain a link to this , but nothing will link to editWindow , so eventually garbage will be collected and the link to this will be discarded. Therefore, it should not cause memory leaks ...

If you want to be sure that there will be no problems, you can unsubscribe from the event:

 InitializeComponent(); Messenger.Default.Register<EditorInfo>(this, (editorData) => { ChildWindow editWindow = new EditWindow(); EventHandler handler = (s, args) => { editWindow.Closed -= handler; if (editWindow.DialogResult == true) // Send data back to VM else // Send 'Cancel' back to VM }; editWindow.Closed += handler; editWindow.Show(); }); 
+4
source share

All Articles