So I have been doing some research on correctly unhooking event handlers from my view model to prevent Memory leaks.
Say I have a View Model like so:
class MyViewModel
{
private List<MyObject> _myObjects;
public List<MyObject> MyObjects
{
get { return _myObjects; }
set { _myObjects = value; }
}
public MyViewModel()
{
for (int i = 0; i < 10; i++)
{
var obj = new MyObject();
obj.MySampleEvent += Obj_MySampleEvent ;
}
}
private void Obj_MySampleEvent (object sender, EventArgs e)
{
//do something
}
}
Now Initially I found This link Which said Implement IDisposable
and add a Dispose
Method:
public void Dispose()
{
foreach (var obj in MyObjects)
{
obj.MySampleEvent -= Obj_MySampleEvent;
}
}
but this wasn't getting called when I would of thought. It seemed to be erratic, Sometimes never even called at all? So I decided to search "When does dispose get called" which lead me to this link explaining that Dispose
gets called by the Finaliser
/ Destructor
Which lead me onto my final piece of research is that I remember people saying do not unhook event Handlers in the Destructor
because it will never get called, from this link.
So I just wanted to clarify finally.. What is the correct way of unhooking event handlers in a ViewModel?