什么是“弱事件"?WPF 应用程序中使用的模式? [英] What is the "Weak Event" pattern used in WPF applications?

查看:27
本文介绍了什么是“弱事件"?WPF 应用程序中使用的模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

WindowsBase DLL 定义了带有摘要的 IWeakEventListener 事件:

The WindowsBase DLL defines the IWeakEventListener event with summary:

为希望通过 WeakEvent 模式和 System.Windows.WeakEventManager 接收事件的类提供事件侦听支持.

Provides event listening support for classes that expect to receive events through the WeakEvent pattern and a System.Windows.WeakEventManager.

这种模糊的描述并没有描述WeakEvent 模式"究竟是什么.

This vague description doesn't describe what the 'WeakEvent pattern' actually is.

那么,这种模式是什么,为什么要使用它以及它在 WPF 应用程序之外是否有用?

So, what is this pattern, why is it used and is it useful outside of WPF applications?

EDIT 已经有一些很好的答案,但没有人讨论过这种模式在 WPF 应用程序之外是否有用.在我看来,弱事件模式(如依赖属性)与 WPF API 和 DLL 密不可分.是否有可用于非 WPF 应用程序的等效实现?

EDIT Some good answers already, but no one has talked about whether this pattern is useful outside of WPF applications. It seems to me that the weak event pattern, like dependency properties, is inextricably linked to the WPF APIs and DLLs. Is there an equivalent implementation available for non-WPF applications?

推荐答案

重要的一点在备注:

遵循以下原则的主要原因WeakEvent 模式是当事件发生时源的对象生命周期是可能独立于事件听众.使用中心事件调度 WeakEventManager允许侦听器的处理程序垃圾收集,即使来源对象持久化

The principal reason for following the WeakEvent pattern is when the event source has an object lifetime that is potentially independent of the event listeners. Using the central event dispatching of a WeakEventManager allows the listener's handlers to be garbage collected even if the source object persists

所以如果你有 publishersubscriber 对象,那么通常在 subscriber 订阅了 publisher 之后事件,subscriber 不能被垃圾回收.弱事件模式使两个弱"之间的链接(如在 WeakReference) 这样就没有这种依赖性了.(另一种方法是在 subscriber 想要获得垃圾收集资格时取消订阅该事件,但这会变得混乱.)

So if you have publisher and subscriber objects, then normally after subscriber has subscribed to publisher's event, subscriber can't be garbage collected. The weak event pattern makes the link between the two "weak" (as in WeakReference) so that there isn't this dependency. (The alternative is to unsubscribe from the event when subscriber wants to become eligible for garbage collection, but that gets messy.)

这篇关于什么是“弱事件"?WPF 应用程序中使用的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆