上一篇blog 提到了Delay的Weak Event Pattern , 使用了如下代码:
_weakEventListener.OnDetachAction = (weakEventListener) =>
newNotifyCollectionChanged.CollectionChanged -= weakEventListener.OnEvent;
在上面的匿名委托中使用了一个参数,避免使用closure而导致隐藏的引用造成内存泄露。
什么是Closure
closures allow you to encapsulate some behaviour, pass it around like any other object, and still have access to the context in which they were first declared. This allows you to separate out control structures, logical operators etc from the details of how they're going to be used. The ability to access the original context is what separates closures from normal objects, although closure implementations typically achieve this using normal objects and compiler trickery
为什么Closure会产生隐藏的引用?匿名委托的三种可能结果 中,后两种就是这种情形。
Keiner的一篇blog 给出了详细的解释以及对Silverlight Toolkit中内部类WeakEventListener的改造