// Removes the left-over weak references for entries in the dictionary // whose key has already been reclaimed by the garbage // collector. This will reduce the dictionary's Count by the number // of dead key-value pairs that were eliminated. public void RemoveCollectedEntries() { List <object> toRemove = null; foreach (KeyValuePair <object, TValue> pair in this.dictionary) { WeakKeyReference <TKey> weakKey = (WeakKeyReference <TKey>)(pair.Key); if (!weakKey.IsAlive) { if (toRemove == null) { toRemove = new List <object>(); } toRemove.Add(weakKey); } } if (toRemove != null) { foreach (object key in toRemove) { this.dictionary.Remove(key); } } }
public override void Add(TKey key, TValue value) { if (key == null) { throw new ArgumentNullException("key"); } WeakKeyReference <TKey> weakKey = new WeakKeyReference <TKey>(key, this.comparer); this.dictionary.Add(weakKey, value); }
public int GetHashCode(object obj) { WeakKeyReference <T> weakKey = obj as WeakKeyReference <T>; if (weakKey != null) { return(weakKey.HashCode); } return(this.comparer.GetHashCode((T)obj)); }
public override IEnumerator <KeyValuePair <TKey, TValue> > GetEnumerator() { foreach (KeyValuePair <object, TValue> kvp in this.dictionary) { WeakKeyReference <TKey> weakKey = (WeakKeyReference <TKey>)(kvp.Key); TKey key = weakKey.Target; TValue value = kvp.Value; if (weakKey.IsAlive) { yield return(new KeyValuePair <TKey, TValue>(key, value)); } } }
private static T GetTarget(object obj, out bool isDead) { WeakKeyReference <T> wref = obj as WeakKeyReference <T>; T target; if (wref != null) { target = wref.Target; isDead = !wref.IsAlive; } else { target = (T)obj; isDead = false; } return(target); }
protected override void SetValue(TKey key, TValue value) { WeakKeyReference <TKey> weakKey = new WeakKeyReference <TKey>(key, this.comparer); this.dictionary[weakKey] = value; }