WeakReference and event handling

21,663

Solution 1

It is good to get in the habit of unsubscribing from events when you can, but sometimes there isn't an obvious "cleanup" method where it can be done. We recently posted a blog article on this subject; it includes methods that make it easy to subscribe to an event with a WeakReference.

Solution 2

Weak delegate pattern is something that should be there in CLR. Normal events exhibit "notify me while you are alive" semantics, while often we need "notify me while I'm alive". Just having delegate on WeakReference is wrong, because delegate is an object too and even when recepient is still alive and have incoming references, delegate itself is only being referenced by said WeakReference and will be collected instantly. See this old post for an example of implementation.

Solution 3

Weak references in their own right, don't solve the problem as the delegate holds the reference. In the Composite Application Library which ships with Prism (www.microsoft.com/compositewpf) there is a WeakDelegate class that you could pull from the source. The WeakDelegate basically ues reflection and creates a delegate only for a moment in time and then releases it, thereby no holding any pointers. Within CAL it is used by the EventAggregator class, but you are free to rip it out for your own usage as it is under MS-PL.

Share:
21,663
Cherian
Author by

Cherian

Co-founder of Cucumbertown. Ex-Zynga, cook, dreamer and lots more… Blog Twitter Facebook LinkedIn Bio Google Reader Shared Items

Updated on November 03, 2020

Comments

  • Cherian
    Cherian over 3 years

    Is it a good practice to implement event handling through WeakReference if that event is the only thing holding the reference and that we would need the object to be garbage collected?

    As an argument to this:

    Folks say that if you subscribe to something it’s your responsibility to unsubscribe and you should do it.