Fix WeakKeyDictionary bug, using wring keyHashCode at some points

pull/2/head
Harald Wolff 2019-10-08 12:15:12 +02:00
parent 26b5f820a8
commit d17b290d9a
2 changed files with 13 additions and 9 deletions

View File

@ -78,8 +78,9 @@ namespace ln.types.collections
WeakKeyValuePair<K, V> weakKeyValuePair = FindKeyValuePair(key);
if (weakKeyValuePair == null)
{
weakKeyValuePair = new WeakKeyValuePair<K, V>(key, value);
store.Add(key.GetHashCode(), weakKeyValuePair);
int keyHashCode = GetKeyHashcode(key);
weakKeyValuePair = new WeakKeyValuePair<K, V>(keyHashCode, key, value);
store.Add(keyHashCode, weakKeyValuePair);
return false;
} else if (replace)
{
@ -97,7 +98,7 @@ namespace ln.types.collections
{
List<K> keys = new List<K>();
foreach (WeakKeyValuePair<K,V> weakKeyValuePair in store.Values)
foreach (WeakKeyValuePair<K,V> weakKeyValuePair in store.Values.ToArray())
{
if (weakKeyValuePair.IsStrong)
keys.Add(weakKeyValuePair.Key);
@ -205,10 +206,10 @@ namespace ln.types.collections
public V Value { get; set; }
public WeakKeyValuePair(TK key,V value)
public WeakKeyValuePair(int keyHashCode,TK key,V value)
{
reference = new WeakReference<TK>(key);
keyHashCode = value.GetHashCode();
this.keyHashCode = keyHashCode;
Value = value;
}

View File

@ -9,7 +9,7 @@ namespace ln.types.test
{
class KeyClass
{
static int next = 1;
static int next = 0;
public readonly int Value = next++;
@ -59,11 +59,14 @@ namespace ln.types.test
Thread.Sleep(250);
GC.Collect();
GC.Collect();
GC.Collect();
Thread.Sleep(250);
Thread.Sleep(250);
Assert.AreEqual(keys.Length-2, testDict.Keys.Count);
GC.Collect();
Assert.AreEqual(keys.Length-2, testDict.Keys.Count);
KeyClass key0 = new KeyClass(0);