Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>What you really need in this case is not some way to automatically detach but to ensure that the reference held by the long lived object does not keep the behaviour (and therefore everything else it has a reference to) from being garbage collected.</p> <p>This is acheived by implementing a Mediator pattern. The concept is that you don't give the long-lived object a delegate with a reference to your <code>Behaviour</code>, instead you create a Mediator class as a go-between. The mediator attaches to the long-lived objects event and holds a <a href="http://msdn.microsoft.com/en-us/library/system.weakreference(v=VS.95).aspx" rel="nofollow noreferrer">WeakReference</a> to the behaviour. When the long-lived object fires the event the mediator checks that the <code>WeakReference</code> is still alive, if so calls a method on it to pass on the event. If when the event occurs the mediator finds that the <code>WeakReference</code> is no longer alive it detaches its event handler from the long lived object.</p> <p>Hence there is nothing stopping the behaviour and everything else involved from being garbage collected all thats left is a very small mediator instance with a dead reference still attached to the long-lived object. Since these mediators are tiny they don't represent a real problem and even those will disappear the next time the event fires.</p> <p>Fortunately you don't have to build this stuff yourself others have already done it. It is called the <code>WeakEventListener</code>. This blog: <a href="http://blogs.msdn.com/delay/archive/2010/02/25/highlighting-a-weak-contribution-enhancements-make-preventing-memory-leaks-with-weakeventlistener-even-easier.aspx" rel="nofollow noreferrer">Highlighting a "weak" contribution; Enhancements make preventing memory leaks with WeakEventListener even easier!</a> has an excellent set of links on the subject.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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