Weak events in .NET?

后端 未结 9 1995
没有蜡笔的小新
没有蜡笔的小新 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:34

    Be careful when using weak events implementations. Weak events appear to remove from the subscriber the responsibility of unsubscribing from the event (or message). In that case event handlers may be invoked even after the subscriber "goes out of scope". Take a subscriber that does not explicitly unsubscribe and that becomes garbage collectable but is not yet garbage collected. The weak event manager will not be able to detect that state and because of that it will still call the event handler of that subscriber. This can lead to all kind of unexpected side effects.

    See more details at The Weak Event Pattern is Dangerous.
    See this source code that illustrates this issue using the MvvMCross messaging plugin as a weak event manager.

提交回复
热议问题