Ran a handful of times into the term lightweight event
. The texts were not accompanied by any code snippets to figure out the idea behind the term.
I would really appreciate it if anyone could explain what are lightweight events about and throw in an example.
views:
55answers:
1When you add an event handler to an event (or a method group to a delegate, really), the delegate will hold a reference to the object that the method group is on, if it is an instance method.
In other words, the object firing the events will hold onto your object that is receiving events while it is subscribed to the event.
Because of this, if you are done using that object that is receiving events, it still lives on (and responds to events) even if you are done with it and release all the references (without unsubscribing).
This leads to the desire for lightweight events
, which are events that don't hold onto a reference.
This is not offered by default in .NET framework out-of-the-box, so if you wanted to implement this, you would have to use the add and remove accessors when declaring your event along with a WeakReference to store the delegate that is passed through the implicit value parameter.
Then, when you fire the events, you would check your WeakReference collection (you have to maintain that separately to do this), specifically the IsAlive and Target properties to determine if the delegate has been collected. If not, then you would execute it, otherwise, you would pass it by (and compress your list, most likely).