深入理解弱引用与垃圾回收机制
1. 弱引用概述
在垃圾回收(GC)机制中,普通引用会被GC追踪,但弱引用有所不同。GC不会追踪弱引用,如果一个对象只能通过弱引用访问,GC会将其视为不可达对象并进行回收。弱引用就像是告诉公共语言运行时(CLR):“别因为我而保留这个对象,但只要其他地方还需要它,我希望能访问到它”。
2. 弱引用在缓存中的应用
下面是一个使用 WeakReference<T> 的缓存示例:
public class WeakCache<TKey, TValue>
where TKey : notnull
where TValue : class
{
private readonly Dictionary<TKey, WeakReference<TValue>> _cache = new Dictionary<TKey, WeakReference<TValue>>();
public void Add(TKey key, TValue value)
{
_cache.Add(key, new WeakReference<TValue>(value));
}
public bool TryGetValue(TKey key, [NotNullWhen(true)] out TValue? cachedItem)
{
if (_cache.TryGetValu
超级会员免费看
订阅专栏 解锁全文
927

被折叠的 条评论
为什么被折叠?



