什么是"弱事件"在WPF应用程序中使用的模式?应用程序、模式、事件、QUOT

2023-09-02 21:45:14 作者:岁月沧海

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?

推荐答案

最重要的一点是,在备注:

The important bit is in the remarks:

为继的主要原因   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.)

 
精彩推荐
图片推荐