Weak References



Although the GC will follow ordinary references in a reachable object’s fields, it is possible to hold a weak reference. The GC does not follow weak references, so if the only way to reach an object is through weak references, the GC behaves as though the object is not reachable, and will remove it. A weak reference provides a way of telling the CLR, “do not keep this object around on my account, but for as long as something else needs it, I would like to be able to get access to it.

Using weak references in a cache
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;
        }
    }
}