Sumel007
Topic Author
Posts: 30
Joined: 19 Mar 2020, 10:50

Where should weak events be used to avoid memory leaks?

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:
protected override bool ConnectEvent(object source, string eventName, string handlerName)
        {
            if (eventName == "Click" && handlerName == "LeftButtonClick")
            {
                ((Button)source).Click += this.LeftButtonClick;
                return true;
            }
            return false;
        }
Or do I then need to unconnect this event in some method?
 
User avatar
sfernandez
Site Admin
Posts: 2991
Joined: 22 Dec 2011, 19:20

Re: Where should weak events be used to avoid memory leaks?

27 Mar 2023, 13:54

Hi,
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?
Our native library keeps a reference to managed objects while they are strong referenced, so when hooking to events it happens always unless weak references are used. We have to update our doc and samples to make this more clear.
I want to make sure that the same is not necessary for the events when implementing the ConnectEvent method
Using weak references is necessary also when implementing the ConnectEvent method:
protected override bool ConnectEvent(object source, string eventName, string handlerName)
{
  WeakReference wr = new WeakReference(this);
  if (eventName == "Click" && handlerName == "LeftButtonClick")
  {
    ((Button)source).Click += (s, e) => { ((MainWindow)wr.Target)?.LeftButtonClick(s, e); };
    return true;
  }
  return false;
}
Cheers!

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 18 guests