Please help me again. This is the weak dictionary i have created. It is compiling correctly. But when i test it with GC.Collect(), i can still refer to the weak reference values even after calling GC.Collect() method. How is it possible? What is wrong in my code.
<pre>namespace TryWeakDictionary{ public class WeakReference<T> : WeakReference { public WeakReference(T val) : base(val, false) { } }
public class WeakDictionary<TKey, TValue> : IDictionary<TKey,TValue> { private Dictionary<TKey, WeakReference<TValue>> weakDictionary = new Dictionary<TKey, WeakReference<TValue>>(); public void Add(TKey key, TValue value) { WeakReference<TValue> weakRef = new WeakReference<TValue>(value); this.weakDictionary.Add(key, weakRef); }
public void Clear() { this.weakDictionary.Clear(); }
public bool ContainsKey(TKey key) { return this.weakDictionary.ContainsKey(key); }
public void Remove(TKey key) { this.weakDictionary.Remove(key); }
public bool TryGetValue(TKey key, out TValue value) { WeakReference<TValue> weakReference; if (this.weakDictionary.TryGetValue(key, out weakReference) && weakReference.IsAlive) { value = (TValue)weakReference.Target; return true; } else { weakDictionary.Remove(key); value = default(TValue); return false; } } }}</pre>