Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When 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.</p> <p>In other words, the object firing the events will hold onto your object that is receiving events while it is subscribed to the event.</p> <p>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).</p> <p>This leads to the desire for <code>lightweight events</code>, which are events that don't hold onto a reference.</p> <p>This is <em>not</em> offered by default in .NET framework out-of-the-box, so if you wanted to implement this, you would have to use the <a href="http://msdn.microsoft.com/en-us/library/8627sbea(VS.71).aspx" rel="nofollow noreferrer">add and remove accessors when declaring your event</a> along with a <a href="http://msdn.microsoft.com/en-us/library/system.weakreference.aspx" rel="nofollow noreferrer">WeakReference</a> to store the delegate that is passed through the implicit value parameter.</p> <p>Then, when you fire the events, you would check your WeakReference collection (you have to maintain that separately to do this), specifically the <a href="http://msdn.microsoft.com/en-us/library/system.weakreference.isalive.aspx" rel="nofollow noreferrer">IsAlive</a> and <a href="http://msdn.microsoft.com/en-us/library/system.weakreference.target.aspx" rel="nofollow noreferrer">Target</a> 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).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload