Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

.net - What is the "Weak Event" pattern used in WPF applications?

The WindowsBase DLL defines the IWeakEventListener event with summary:

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

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The important bit is in the remarks:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...