How do weak events work?
Asked Answered
R

1

17

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:

  1. I understand that when an object subscribes to an event, the source of the event has to hold a reference to the subscriber.
  2. 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.
  3. 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.

Retardment answered 9/5, 2012 at 19:18 Comment(0)
F
18

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"

Filth answered 9/5, 2012 at 19:28 Comment(2)
@ChrisSinclair link is down :(Duiker
@SuperJMN: Thanks. Here's an updated link: bkiener.wordpress.com/2010/02/11/…Amorphism

© 2022 - 2024 — McMap. All rights reserved.