I'm currently learning WPF and have stumbled upon the concept of weak events but I am really struggling to 'get it'. I have read countless articles on Stackoverflow and looked at code samples but it just isn't sinking in.
Here's my dilemma:
- I understand that when an object subscribes to an event, the source of the event has to hold a reference to the subscriber.
- I also understand that if the subscriber goes out of scope or is explicitly destroyed but the event source is not destroyed then the subscriber will not be garbage collected because the event source still retains a reference to the subscriber.
- A common method of avoiding this is to explicitly un-subscribe the subscriber from the source before the object is destroyed. I understand that this can be a problem if the programmer is not able to determine when this will occur.
So from the above I understand how the use of events can cause memory leaks and why there is a need for a weak reference pattern but what is stopping me from understanding is how does the weak event pattern actually achieve this goal? What does it do differently?
Surely even if there is a class that manages events it still has to subscribe and un-subscribe the handlers to / from the source, hence references must exist, giving the same problems with the standard way of using events.
Someone please explain to me what fundamental concept I am missing or misunderstanding and help me to 'get' the weak event pattern.