Skip to content

Instantly share code, notes, and snippets.

@jeiea
Created July 15, 2018 21:04
Show Gist options
  • Save jeiea/c5a6f3b06abea54fcff48c469d694c73 to your computer and use it in GitHub Desktop.
Save jeiea/c5a6f3b06abea54fcff48c469d694c73 to your computer and use it in GitHub Desktop.
Not thread safe..
public class WeakCache<T> where T : class {
private Dictionary<object, WeakReference<T>> Index
= new Dictionary<object, WeakReference<T>>();
public bool TryGetValue(object key, out T val) {
if (Index.TryGetValue(key, out WeakReference<T> weak))
if (weak.TryGetTarget(out T target)) {
val = target;
return true;
}
val = null;
return false;
}
public T Get(object key, Func<T> gen) {
if (TryGetValue(key, out T target))
return target;
T val = gen();
Index[key] = new WeakReference<T>(val);
return val;
}
public void Set(object key, T val) {
Index[key] = new WeakReference<T>(val);
}
public T this[object key] {
get => TryGetValue(key, out T val) ? val : throw new KeyNotFoundException();
set => Set(key, value);
}
public void Clear() => Index.Clear();
public void Sweep() {
Index.Where(x => !x.Value.TryGetTarget(out T d))
.Select(x => x.Key).ToList().ForEach(x => {
Index.Remove(x);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment