Weak events in .NET?

后端 未结 9 1979
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 16:37

If object A listens to an event from object B, object B will keep object A alive. Is there a standard implementation of weak events that would prevent this? I know WPF has s

9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-04 17:35

    What advantages does Dustin's implementation have compared to the WPF's WeakEventManager class which simply wraps the target object as well as the delegate into a weak reference:

    public Listener(object target, Delegate handler)
      {
           this._target = new WeakReference(target);
           this._handler = new WeakReference((object) handler);
      }
    

    In my opinion this approach is more flexible, since it does not require the implementation to pass the target instance as a parameter during the invocation of the event handler:

    public void Invoke(object sender, E e)
            {
                T target = (T)m_TargetRef.Target;
    
                if (target != null)
                    m_OpenHandler(target, sender, e);
    

    This also allows the use of anomymous methods instead of an instance method (that seems to be also a disadvantage of the Dustin's implementation).

提交回复
热议问题