Following the MVVM pattern I'm trying to wire up the display of a child window by the View in response to a request from the View Model.
Using the MVVM-Light Messenger the View will Register for the request to display the child window in the constructor of the View as so:
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 subscribing to the ChildWindow Closed event using a Lambda cause problems for garbage collection. Or put it another way, when (if ever) will the editWindow become unreferenced and so a candidate for garbage collection.
A memory leak starts when a program requests a chunk of memory from the operating system for itself and its data. As a program operates, it sometimes needs more memory and makes an additional request.
The memory leak occurs, when a piece of memory which was previously allocated by the programmer. Then it is not deallocated properly by programmer. That memory is no longer in use by the program. So that place is reserved for no reason. That's why this is called the memory leak.
In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.
Use reference objects to avoid memory leaks ref package, you can work with the garbage collector in your program. This allows you to avoid directly referencing objects and use special reference objects that the garbage collector easily clears. The special subclasses allow you to refer to objects indirectly.
editWindow
will keep a reference to this
, but nothing will have a reference to editWindow
, so it will eventually be garbage collected, and the reference to this
will be discarded. So it shouldn't cause any memory leak...
If you want to be sure there will be no problem, 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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With