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

查看:337
本文介绍了什么是“弱事件” 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?

编辑已经有一些很好的答案,但没有人谈到这个模式在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

所以如果你有发布者订阅者对象,那么通常在订阅者已订阅发布者的活动,订阅者可以'被垃圾收集。弱事件模式使两个弱之间的链接(如 WeakReference ),以便没有这种依赖。 (另一种方法是取消订阅订阅者希望有资格进行垃圾回收的事件,但会变得混乱)。

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天全站免登陆