Where should weak events be used to avoid memory leaks?
Posted: 16 Mar 2023, 13:31
Hi!
I am trying to track down memory leaks and reading your documentation regarding that. In the documentation it is recommended to create weak references when attaching to events in code behind https://www.noesisengine.com/docs/Gui.C ... k-events-c . I understand why that would be the case when subcribing to events from some other class (ie. if my control was to subscribe to some model class's event with a strong reference, my control would live as long as the model class lives, since the model class has a reference to my control in order to invoke the event properly). But in the example, MainWindow subscribes to an event from itself, so shouldn't it be garbage collected normally? It will hold a reference to itself, which should not be an issue the way I understand it, since the source and listener is the same object? Is there something I am missing?
And since these subscriptions to events have to be changed to WeakReferences, I want to make sure that the same is not necessary for the events when implementing the ConnectEvent method:
Or do I then need to unconnect this event in some method?
I am trying to track down memory leaks and reading your documentation regarding that. In the documentation it is recommended to create weak references when attaching to events in code behind https://www.noesisengine.com/docs/Gui.C ... k-events-c . I understand why that would be the case when subcribing to events from some other class (ie. if my control was to subscribe to some model class's event with a strong reference, my control would live as long as the model class lives, since the model class has a reference to my control in order to invoke the event properly). But in the example, MainWindow subscribes to an event from itself, so shouldn't it be garbage collected normally? It will hold a reference to itself, which should not be an issue the way I understand it, since the source and listener is the same object? Is there something I am missing?
And since these subscriptions to events have to be changed to WeakReferences, I want to make sure that the same is not necessary for the events when implementing the ConnectEvent method:
Code: Select all
protected override bool ConnectEvent(object source, string eventName, string handlerName)
{
if (eventName == "Click" && handlerName == "LeftButtonClick")
{
((Button)source).Click += this.LeftButtonClick;
return true;
}
return false;
}