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:
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.
What you are missing is that Weak Events (which use Weak References under the covers, which in turn use a GCHandle) are leveraging built-in CLR behavior for the particular case of needing to access an object without holding a strong reference to it- that is, they are not constrained by the normal "rules" that your application code is subject to.
See http://sankarsan.wordpress.com/2008/08/09/weak-references/
Behind the scenes, the WeakEventManager is holding a weak reference to the event subscriber. If the subscriber happens to be GC'd before the event is raised, the WeakEventManager just shrugs and says "OK, that guy's dead, I'm just going to stop trying to notify him of this event from now on"
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