闭合 (Closure)与隐藏的引用

本文探讨了Closure的概念及其如何导致内存泄露的问题,并通过具体代码示例进行了解释。此外,还介绍了如何通过改造WeakEventListener来避免此类问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上一篇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的改造

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值