Weak events in .NET?

2019-01-13 04:42发布

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 some mechanism but I am looking for something not tied to WPF. I am guessing the solution should use weak references somewhere.

9条回答
Lonely孤独者°
2楼-- · 2019-01-13 05:25

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).

查看更多
ら.Afraid
3楼-- · 2019-01-13 05:26

Using the recommended Dispose() pattern, where you consider events a managed resource to clean up, should handle this. Object A should unregister itself as a listener of events from object B when it's disposed...

查看更多
Rolldiameter
4楼-- · 2019-01-13 05:29

There's also a solution that works in Silverlight/WP7 which uses Linq expressions instead of MSIL emit.

http://socialeboladev.wordpress.com/2012/09/23/weak-event-implementation-that-works-for-any-event-type/

查看更多
登录 后发表回答