-
Notifications
You must be signed in to change notification settings - Fork 56
/
WeakCache.cs
35 lines (32 loc) · 936 Bytes
/
WeakCache.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;
using System.Collections.Generic;
namespace WeakRefs
{
public class WeakCache<TKey, TValue> 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, out TValue cachedItem)
{
WeakReference<TValue> entry;
if (_cache.TryGetValue(key, out entry))
{
bool isAlive = entry.TryGetTarget(out cachedItem);
if (!isAlive)
{
_cache.Remove(key);
}
return isAlive;
}
else
{
cachedItem = null;
return false;
}
}
}
}