Skip to content

Instantly share code, notes, and snippets.

@guhou
Created April 29, 2015 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guhou/c45b93ca3621cafb7045 to your computer and use it in GitHub Desktop.
Save guhou/c45b93ca3621cafb7045 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
public class Cache<K, V> where V : class
{
private readonly Dictionary<K, WeakReference<V>> _data;
public Cache()
{
_data = new Dictionary<K, WeakReference<V>>();
}
public void Add(K key, V value)
{
_data[key] = new WeakReference<V>(value);
}
public void Remove(K key)
{
_data.Remove(key);
}
public bool TryGetValue(K key, out V result)
{
WeakReference<V> weakReference;
// Does the dictionary contain the key?
if (_data.TryGetValue(key, out weakReference))
{
// Check if the reference target is still alive.
if (weakReference.TryGetTarget(out result))
{
// Found the reference- we're done here.
return true;
}
else
{
// Target reference was dead; might as well remove it from
// the dictionary.
Remove(key);
return false;
}
}
else
{
// Didn't find anything good, return false.
result = null;
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment