What is the “Weak Event” pattern used in WPF applications?

跟風遠走 提交于 2019-11-27 19:50:45

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

WeakEvent Patterns

Subscribing to events can result in the subscribers being not collected. You'd assume that the object would be collected as you're holding no other reference to it - However the event publisher holds onto the listener object and keeps it in memory (unless it explicitly unsubscribes, in which case you need to know exactly when to unsubscribe). A managed leak.

As a thumb rule, if the event publisher is going to hang around for longer than the listener, you can run into this issue and should check this out.

WeakEvents should help you out here in that the object would be collected if the only active references to it are 'Weak'. You should be concerned with this pattern only if you plan to develop new controls, which usually expose lots of events.

The basic idea is similar to WeakReference w.r.t. garbage collection.

Jowen

In .NET 4.5, there's improved support for establishing a weak reference to an event.

Instead of

source.Event += OnEvent;

You can use the new WeakEventManager<TEventSource, TEventArgs>:

WeakEventManager<EventSource, EventArgs>.AddHandler(source, "Event", OnEvent);

Read more here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!