Created
April 29, 2015 07:20
-
-
Save guhou/c45b93ca3621cafb7045 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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