码迷,mamicode.com
首页 > 其他好文 > 详细

Weak Event Patterns

时间:2015-10-21 22:23:27      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:

https://msdn.microsoft.com/en-US/library/aa970850(v=vs.100).aspx

In applications, it is possible that handlers that are attached to event sources will not be destroyed in coordination with the listener object that attached the handler to the source.

This situation can lead to memory leaks.

Windows Presentation Foundation (WPF) introduces a design pattern that can be used to address this issue, by providing a dedicated manager class for particular events and implementing an interface on listeners for that event.

This design pattern is known as the weak event pattern.

 

Why Implement the Weak Event Pattern?

Listening for events can lead to memory leaks. The typical technique for listening to an event is to use the language-specific syntax that attaches a handler to an event on a source.

For example, in C#, that syntax is: source.SomeEvent += new SomeEventHandler(MyEventHandler).

 

This technique creates a strong reference from the event source to the event listener.

Ordinarily, attaching an event handler for a listener causes the listener to have an object lifetime that is influenced by the object lifetime of the source (unless the event handler is explicitly removed).

But in certain circumstances, you might want the object lifetime of the listener to be controlled by other factors, such as whether it currently belongs to the visual tree of the application, and not by the lifetime of the source.

Whenever the source object lifetime extends beyond the object lifetime of the listener, the normal event pattern leads to a memory leak: the listener is kept alive longer than intended.

 

The weak event pattern is designed to solve this memory leak problem.

The weak event pattern can be used whenever a listener needs to register for an event, but the listener does not explicitly know when to unregister.

The weak event pattern can also be used whenever the object lifetime of the source exceeds the useful object lifetime of the listener. (In this case, useful is determined by you.)

The weak event pattern allows the listener to register for and receive the event without affecting the object lifetime characteristics of the listener in any way.

In effect, the implied reference from the source does not determine whether the listener is eligible for garbage collection.

The reference is a weak reference, thus the naming of the weak event pattern and the related APIs.

The listener can be garbage collected or otherwise destroyed, and the source can continue without retaining noncollectible handler references to a now destroyed object.

 

Weak Event Patterns

标签:

原文地址:http://www.cnblogs.com/chucklu/p/4899034.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!