Beispiel #1
0
        public void TestCollect4()
        {
            var dictionary = new WeakKeyDictionary <object, int>();
            var key1       = new Key(1, 9001);
            var key4       = new Key(4, 9001);

            new Action(() =>
            {
                dictionary.Add(key1, 1);
                dictionary.Add(new Key(2, 9001), 2);
                dictionary.Add(new Key(3, 9001), 3);
                dictionary.Add(key4, 4);
            })();

            GC.Collect();
            GC.WaitForPendingFinalizers();

            dictionary.Count.Should().Be(4);
            dictionary.Collect();
            dictionary.Count.Should().Be(2);
            dictionary[key1].Should().Be(1);
            dictionary[key4].Should().Be(4);
            dictionary._freeCount.Should().Be(2, "Because 2 previously used entries were reclaimed");

            EnsureIntegrity(dictionary);
        }
Beispiel #2
0
        public void TestAdd8()
        {
            var dictionary = new WeakKeyDictionary <object, int>();
            var key1       = new Key(1, 42);
            WeakReference <Key> weakKey2 = null;
            var key3 = new Key(3, 42);

            new Action(() =>
            {
                var key2 = new Key(2, 42);
                weakKey2 = new WeakReference <Key>(key2);
                dictionary.Add(key1, 1);
                dictionary.Add(key2, 2);
                dictionary.Add(key3, 3);
            })();

            dictionary.Count.Should().Be(3);
            dictionary._freeCount.Should().Be(0);

            GC.Collect();
            GC.WaitForPendingFinalizers();

            // This is a special case that tests that iterating over an entry within a bucket
            // that has been collected by the GC works as expected: There has been a bug that caused
            // the iteration within the bucket to completely stop.

            var key4 = new Key(1, 42);

            new Action(() => dictionary.Add(key4, 4))
            .Should().Throw <ArgumentException>()
            .WithMessage("An item with the same key has already been added.");

            dictionary.Count.Should().Be(2);
            dictionary._freeCount.Should().Be(1);
        }
Beispiel #3
0
        public void TestAdd2()
        {
            var dictionary = new WeakKeyDictionary <string, int>();

            dictionary.Add("Foobar", 42);
            dictionary.Add("Klondyke Bar", 9001);
            dictionary.Count.Should().Be(2);
            dictionary.ContainsKey("Foobar").Should().BeTrue();
            dictionary.ContainsKey("Klondyke Bar").Should().BeTrue();
            dictionary.Version.Should().Be(2);

            EnsureIntegrity(dictionary);
        }
Beispiel #4
0
        public void TestAdd3()
        {
            var dictionary = new WeakKeyDictionary <string, int>();

            dictionary.Add("Foobar", 42);
            new Action(() => dictionary.Add("Foobar", 42))
            .Should().Throw <ArgumentException>()
            .WithMessage("An item with the same key has already been added.");

            dictionary.Count.Should().Be(1);
            dictionary.ContainsKey("Foobar").Should().BeTrue();
            dictionary.Version.Should().Be(1);

            EnsureIntegrity(dictionary);
        }
Beispiel #5
0
        public void TestAddPerformance()
        {
            const int num = 1000000;

            var keys           = Enumerable.Range(0, num).Select(i => new object()).ToList();
            var dictionary     = new Dictionary <object, int>();
            var weakDictionary = new WeakKeyDictionary <object, int>();

            var sw1 = new Stopwatch();

            sw1.Start();
            for (int i = 0; i < num; ++i)
            {
                dictionary.Add(keys[i], i);
            }
            sw1.Stop();

            var sw2 = new Stopwatch();

            sw2.Start();
            for (int i = 0; i < num; ++i)
            {
                weakDictionary.Add(keys[i], i);
            }
            sw2.Stop();

            Console.WriteLine("Dictionary.Add: {0}ms", sw1.ElapsedMilliseconds);
            Console.WriteLine("WeakKeyDictionary.Add: {0}ms", sw2.ElapsedMilliseconds);

            sw2.ElapsedMilliseconds.Should().BeLessOrEqualTo(sw1.ElapsedMilliseconds * 10,
                                                             "Because the weak key dictionary should not be slower than by an order of magnitude");
        }
Beispiel #6
0
        public void WeakKeyDictionaryWithData_CopyToEndOfSufficientlyLargeKeyValuePairArray_Succeeds()
        {
            const int NumValuesToAdd = 20;
            var       keeperArounder = new List <KeyValuePair <string, int> >();
            ICollection <KeyValuePair <string, int> > dictionary = new WeakKeyDictionary <string, int>();

            for (int i = 0; i < NumValuesToAdd; ++i)
            {
                var entry = new KeyValuePair <string, int>(i.ToString(), i);
                keeperArounder.Add(entry);
                dictionary.Add(entry);
            }
            Assert.Equal(NumValuesToAdd, dictionary.Count);

            var       destination = new KeyValuePair <string, int> [50];
            const int StartIndex  = 30;

            dictionary.CopyTo(destination, StartIndex);

            for (int i = 0; i < NumValuesToAdd; ++i)
            {
                Assert.Equal(i.ToString(), destination[i + StartIndex].Key);
                Assert.Equal(i, destination[i + StartIndex].Value);
            }
        }
Beispiel #7
0
        public void WeakKeyDictionaryWithData_EnumerateUsingIDictionaryEnumerator_ValidateContents()
        {
            IDictionary dictionary = new WeakKeyDictionary <string, int>();
            var         values     = new[] { -1, 48, 62, 88, -32 };

            for (int i = 0; i < values.Length; ++i)
            {
                dictionary.Add(values[i].ToString(), values[i]);
            }

            var dictionaryEnumerator = dictionary.GetEnumerator();

            while (dictionaryEnumerator.MoveNext())
            {
                var current = dictionaryEnumerator.Current;
                var entry   = dictionaryEnumerator.Entry;
                Assert.Equal(current, entry);
                var key        = dictionaryEnumerator.Key;
                var value      = dictionaryEnumerator.Value;
                var entryKey   = entry.Key as string;
                var entryValue = (int)entry.Value;
                Assert.Equal(key, entryKey);
                Assert.Equal(value, entryValue);
            }
            var disposable = dictionaryEnumerator as IDisposable;

            if (disposable != null)
            {
                disposable.Dispose();
                dictionaryEnumerator = null;
                disposable           = null;
            }
        }
        /// <summary>
        /// Subscribes supplied object to property changed notifications and invokes the provided callback
        /// </summary>
        /// <typeparam name="T">Type of subject</typeparam>
        /// <param name="vmb">Subject</param>
        /// <param name="path">Property path</param>
        /// <param name="callback">Notification callback</param>
        public static void NotifyOn <T>(this T vmb, string path, Action <object, object> callback)
        {
            Dictionary <string, NotificationHelperDp> block;

            if (!_notifiers.TryGetValue(vmb, out block))
            {
                _notifiers.Add(vmb, block = new Dictionary <string, NotificationHelperDp>());
            }
            block.Remove(path);

            NotificationHelperDp binder = new NotificationHelperDp(callback);

            BindingOperations.SetBinding(binder, NotificationHelperDp.BindValueProperty,
#if NET || NETCORE || NETFRAMEWORK
                                         new Binding(path)
            {
                Source = vmb
            });
#else
                                         new Binding {
                Source = vmb, Path = new PropertyPath(path)
            });
#endif
            block.Add(path, binder);
        }
Beispiel #9
0
        public void TestCollect1()
        {
            var dictionary = new WeakKeyDictionary <object, int>();
            WeakReference <object> weakKey = null;

            new Action(() =>
            {
                var key = new ByReferenceClass();
                weakKey = new WeakReference <object>(key);

                dictionary.Add(key, 42);
                dictionary.Count.Should().Be(1);
            })();

            GC.Collect();
            GC.WaitForPendingFinalizers();

            weakKey.Should().NotBeNull();

            dictionary.Collect();
            dictionary.Count.Should().Be(0);
            object unused;

            weakKey.TryGetTarget(out unused).Should().BeFalse("Because the dictionary shouldn't keep the key alive");

            EnsureIntegrity(dictionary);
        }
Beispiel #10
0
        public void TestAdd5()
        {
            var dictionary = new WeakKeyDictionary <Key, int>();
            var key1       = new Key(1, 42);
            var key2       = new Key(2, 42);

            key1.GetHashCode().Should().Be(key2.GetHashCode());
            key1.Equals(key2).Should().BeFalse();

            dictionary.Add(key1, 9);
            dictionary.Add(key2, 10);
            dictionary.Count.Should().Be(2);
            dictionary.ContainsKey(key1).Should().BeTrue();
            dictionary.ContainsKey(key2).Should().BeTrue();

            EnsureIntegrity(dictionary);
        }
Beispiel #11
0
        public void TestAdd9()
        {
            var dictionary = new WeakKeyDictionary <object, string>();

            new Action(() => dictionary.Add(null, "foo"))
            .Should().Throw <ArgumentNullException>()
            .WithMessage("Value cannot be null.\r\nParameter name: key");
        }
Beispiel #12
0
        public void TestIndexer1()
        {
            var dictionary = new WeakKeyDictionary <string, int>();

            dictionary.Add("a", 1);
            dictionary["a"].Should().Be(1);

            EnsureIntegrity(dictionary);
        }
Beispiel #13
0
        public void TestCollect6()
        {
            var dictionary = new WeakKeyDictionary <object, int>();
            var key1       = new object();
            var key2       = new object();

            dictionary.Add(key1, 1337);
            dictionary.Add(key2, 42);
            dictionary.Version.Should().Be(2);
            dictionary.Count.Should().Be(2);

            dictionary.Collect();
            dictionary.Version.Should().Be(2);
            dictionary.Count.Should().Be(2);
            dictionary[key1].Should().Be(1337);
            dictionary[key2].Should().Be(42);

            EnsureIntegrity(dictionary);
        }
Beispiel #14
0
        public void TestTryGetValue1()
        {
            var dictionary = new WeakKeyDictionary <string, int>();

            dictionary.Add("1", 42);
            dictionary.Add("2", 9001);
            dictionary.Add("3", 1337);

            int value;

            dictionary.TryGetValue("1", out value).Should().BeTrue();
            value.Should().Be(42);
            dictionary.TryGetValue("2", out value).Should().BeTrue();
            value.Should().Be(9001);
            dictionary.TryGetValue("3", out value).Should().BeTrue();
            value.Should().Be(1337);

            EnsureIntegrity(dictionary);
        }
Beispiel #15
0
        public void TestIndexer2()
        {
            var dictionary = new WeakKeyDictionary <string, int>();

            dictionary.Add("a", 1);
            new Action(() => { int value = dictionary["b"]; })
            .Should().Throw <ArgumentException>()
            .WithMessage("The given key was not present in the dictionary.");

            EnsureIntegrity(dictionary);
        }
Beispiel #16
0
        public void TestCollect2()
        {
            var dictionary = new WeakKeyDictionary <object, int>();

            new Action(() =>
            {
                dictionary.Add(new Key(1, 9001), 1);
                dictionary.Add(new Key(2, 9001), 2);
                dictionary.Add(new Key(3, 9001), 3);
            })();

            GC.Collect();
            GC.WaitForPendingFinalizers();

            dictionary.Count.Should().Be(3);
            dictionary.Collect();
            dictionary.Count.Should().Be(0);

            EnsureIntegrity(dictionary);
        }
Beispiel #17
0
        public void TestCollect8()
        {
            var dictionary = new WeakKeyDictionary <object, int>();
            var key1       = new Key(1, 9001);
            var key4       = new Key(4, 9001);

            new Action(() =>
            {
                dictionary.Add(key1, 1);
                dictionary.Add(new Key(2, 9001), 2);
                dictionary.Add(new Key(3, 9001), 3);
                dictionary.Add(key4, 4);
            })();

            GC.Collect();
            GC.WaitForPendingFinalizers();

            dictionary.Collect();
            dictionary.Count.Should().Be(2);

            var key2 = new Key(2, 9001);
            var key3 = new Key(3, 9001);

            dictionary.Add(key2, 2);
            dictionary.Add(key3, 3);
            dictionary.Count.Should().Be(4);
            dictionary[key2].Should().Be(2);
            dictionary[key3].Should().Be(3);

            EnsureIntegrity(dictionary);
        }
Beispiel #18
0
        public void TestAdd4()
        {
            var dictionary = new WeakKeyDictionary <string, int>();

            dictionary.Capacity.Should().Be(3);

            dictionary.Add("a", 1);
            dictionary.Add("b", 2);
            dictionary.Add("c", 3);
            dictionary.Capacity.Should().Be(3);

            dictionary.Add("d", 4);
            dictionary.Capacity.Should().BeInRange(3, 7);

            dictionary.Count.Should().Be(4);
            dictionary["a"].Should().Be(1);
            dictionary["b"].Should().Be(2);
            dictionary["c"].Should().Be(3);
            dictionary["d"].Should().Be(4);

            EnsureIntegrity(dictionary);
        }
Beispiel #19
0
        public void WeakKeyDictionary_AddKeyValue_TryGetValueSucceeds()
        {
            const int Value      = 1;
            var       key        = new DisposableTestObject("key");
            var       dictionary = new WeakKeyDictionary <DisposableTestObject, int>();

            dictionary.Add(key, Value);

            int value;

            Assert.True(dictionary.TryGetValue(key, out value));
            Assert.Equal(Value, value);
        }
Beispiel #20
0
        public void WeakKeyDictionary_AddObjectKeyValuePair_TryGetValueSucceeds()
        {
            var    dictionary = new WeakKeyDictionary <object, object>();
            object key        = "Why, it's a Key!";
            object value      = new object();

            dictionary.Add(key, value);

            object valueOut;

            Assert.True(dictionary.TryGetValue("Why, it's a Key!", out valueOut));
            Assert.True(object.ReferenceEquals(value, valueOut));
        }
Beispiel #21
0
        public void WeakKeyDictionaryWithData_ResetIDictionaryEnumerator_ThrowsNotSupportedException()
        {
            IDictionary dictionary = new WeakKeyDictionary <DisposableTestObject, int>();
            var         values     = new[] { -1, 48, 62, 88, -32 };

            for (int i = 0; i < values.Length; ++i)
            {
                dictionary.Add(new DisposableTestObject(values[i].ToString()), values[i]);
            }

            var dictionaryEnumerator = dictionary.GetEnumerator();

            Assert.Throws <NotSupportedException>(() => dictionaryEnumerator.Reset());
        }
Beispiel #22
0
        public void TestAdd6()
        {
            var dictionary = new WeakKeyDictionary <object, int>();
            var key1       = new Key(1, 42);
            WeakReference <Key> weakKey2 = null;
            var key3 = new Key(3, 42);

            new Action(() =>
            {
                var key2 = new Key(2, 42);
                weakKey2 = new WeakReference <Key>(key2);
                dictionary.Add(key1, 1);
                dictionary.Add(key2, 2);
                dictionary.Add(key3, 3);
            })();

            GC.Collect();
            GC.WaitForPendingFinalizers();

            dictionary.Count.Should().Be(3);
            dictionary.Capacity.Should().Be(3);
            dictionary.Version.Should().Be(3);

            weakKey2.Should().NotBeNull();
            Key currentKey2;

            weakKey2.TryGetTarget(out currentKey2).Should().BeFalse("Because the key no longer exists");

            var key4 = new Key(4, 42);

            dictionary.Add(key4, 4);
            dictionary.Count.Should().Be(3);
            dictionary.Capacity.Should().Be(3);
            dictionary.Version.Should().Be(5);

            EnsureIntegrity(dictionary);
        }
Beispiel #23
0
        public void TestTryGetValue2()
        {
            var dictionary = new WeakKeyDictionary <string, int>();
            int value;

            dictionary.TryGetValue("1", out value).Should().BeFalse();
            value.Should().Be(0);

            dictionary.Add("1", 42);

            dictionary.TryGetValue("2", out value).Should().BeFalse();
            value.Should().Be(0);

            EnsureIntegrity(dictionary);
        }
Beispiel #24
0
        public void WeakKeyDictionaryWithData_CopyToBeginningOfSufficientlyLargeKeyValuePairArray_Succeeds()
        {
            const int NumValuesToAdd = 4;
            ICollection <KeyValuePair <string, int> > dictionary = new WeakKeyDictionary <string, int>();

            for (int i = 0; i < NumValuesToAdd; ++i)
            {
                dictionary.Add(new KeyValuePair <string, int>(i.ToString(), i));
            }
            Assert.Equal(NumValuesToAdd, dictionary.Count);

            var       destination = new KeyValuePair <string, int> [50];
            const int StartIndex  = 0;

            dictionary.CopyTo(destination, StartIndex);
        }
Beispiel #25
0
        public void WeakKeyDictionaryWithData_CopyToArrayWithInvalidRank_ThrowsArgumentException()
        {
            const int   NumValuesToAdd    = 2;
            var         weakKeyDictionary = new WeakKeyDictionary <string, int>();
            ICollection dictionary        = weakKeyDictionary;

            for (int i = 0; i < NumValuesToAdd; ++i)
            {
                weakKeyDictionary.Add(new KeyValuePair <string, int>(i.ToString(), i));
            }
            Assert.Equal(NumValuesToAdd, weakKeyDictionary.Count);

            var destination = new KeyValuePair <string, int> [2, 2];

            Assert.Throws <ArgumentException>(() => dictionary.CopyTo(destination, 0));
        }
Beispiel #26
0
        public void WeakKeyDictionaryWithData_CopyToNullKeyValuePairArray_ThrowsArgumentNullException()
        {
            const int NumValuesToAdd = 10;
            var       keeperArounder = new List <KeyValuePair <string, int> >();
            ICollection <KeyValuePair <string, int> > dictionary = new WeakKeyDictionary <string, int>();

            for (int i = 0; i < NumValuesToAdd; ++i)
            {
                var entry = new KeyValuePair <string, int>(i.ToString(), i);
                keeperArounder.Add(entry);
                dictionary.Add(entry);
            }
            Assert.Equal(NumValuesToAdd, dictionary.Count);

            Assert.Throws <ArgumentNullException>(() => dictionary.CopyTo(null, 0));
        }
Beispiel #27
0
        public void WeakKeyDictionary_AddKeyValuePair_TryGetValueSucceeds()
        {
            const int Value          = 2;
            var       key            = new DisposableTestObject("key");
            var       keeperArounder = new List <KeyValuePair <DisposableTestObject, int> >();
            var       dictionary     = new WeakKeyDictionary <DisposableTestObject, int>();

            var entry = new KeyValuePair <DisposableTestObject, int>(key, Value);

            keeperArounder.Add(entry);
            dictionary.Add(entry);

            int value;

            Assert.True(dictionary.TryGetValue(key, out value));
            Assert.Equal(Value, value);
        }
Beispiel #28
0
        public void WeakKeyDictionaryWithData_CopyToKeyValuePairArrayWithIndexResultingInWritePastEndOfArray_ThrowsArgumentException()
        {
            const int NumValuesToAdd = 80;
            var       keeperArounder = new List <KeyValuePair <string, int> >();
            ICollection <KeyValuePair <string, int> > dictionary = new WeakKeyDictionary <string, int>();

            for (int i = 0; i < NumValuesToAdd; ++i)
            {
                var data = new KeyValuePair <string, int>(i.ToString(), i);
                keeperArounder.Add(data);
                dictionary.Add(data);
            }
            Assert.True(NumValuesToAdd >= dictionary.Count);

            var destination = new KeyValuePair <string, int> [50];

            Assert.Throws <ArgumentException>(() => dictionary.CopyTo(destination, 48));
        }
Beispiel #29
0
        public void WeakKeyDictionaryWithData_CopyToKeyValuePairArrayWithNegativeIndex_ThrowsArgumentOutOfRangeException()
        {
            const int NumValuesToAdd = 6;
            var       keeperArounder = new List <KeyValuePair <string, int> >();
            ICollection <KeyValuePair <string, int> > dictionary = new WeakKeyDictionary <string, int>();

            for (int i = 0; i < NumValuesToAdd; ++i)
            {
                var entry = new KeyValuePair <string, int>(i.ToString(), i);
                keeperArounder.Add(entry);
                dictionary.Add(entry);
            }
            Assert.Equal(NumValuesToAdd, dictionary.Count);

            var destination = new KeyValuePair <string, int> [2];

            Assert.Throws <ArgumentOutOfRangeException>(() => dictionary.CopyTo(destination, -1));
        }
Beispiel #30
0
        public void WeakKeyDictionaryAsICollectionWithData_Clear_EnsureEmpty()
        {
            const int NumValuesToAdd = 100;
            ICollection <KeyValuePair <string, int> > dictionary = new WeakKeyDictionary <string, int>();
            var keeperArounder = new List <KeyValuePair <string, int> >();

            for (int i = 0; i < NumValuesToAdd; ++i)
            {
                var entry = new KeyValuePair <string, int>(i.ToString(), i);
                keeperArounder.Add(entry);
                dictionary.Add(entry);
            }
            Assert.Equal(NumValuesToAdd, dictionary.Count);

            dictionary.Clear();

            Assert.Equal(0, dictionary.Count);
        }
        public void Test_WeakKeyDictionary()
        {
            var normalKeyDiction = new Dictionary<TestKey, int>();
            var key = new TestKey("Yohan");
            var keyReference = new WeakReference(key);

            normalKeyDiction.Add(key, 1);
            Assert.AreEqual(1, normalKeyDiction.Count);
            Assert.AreEqual(1, normalKeyDiction[key]);

            Assert.IsTrue(keyReference.IsAlive);

            key = null;
            GC.Collect();

            //Normal Dictionary hold the strong reference to the key.
            Assert.IsTrue(keyReference.IsAlive);

            var weakKeyDictionary = new WeakKeyDictionary<TestKey, int>();

            key = new TestKey("Yohan");
            keyReference = new WeakReference(key);

            weakKeyDictionary.Add(key, 1);
            Assert.AreEqual(1, weakKeyDictionary.Count);
            Assert.AreEqual(1, weakKeyDictionary[key]);

            IList keys = weakKeyDictionary.Keys;
            Assert.AreEqual(1, keys.Count);

            Assert.IsTrue(keyReference.IsAlive);

            key = null;
            GC.Collect();

            //WeakKeyDictionary hold the WeakReference of the key.
            Assert.IsFalse(keyReference.IsAlive);

            GC.KeepAlive(normalKeyDiction);
        }
        public void Test_WeakKeyDictionary_CRUD()
        {
            var weakKeyDictionary = new WeakKeyDictionary<TestKey, int>();

            var key = new TestKey("Yohan");

            weakKeyDictionary.Add(key, 1);
            Assert.AreEqual(1, weakKeyDictionary.Count);
            Assert.AreEqual(1, weakKeyDictionary[key]);

            weakKeyDictionary.Remove(key);
            Assert.AreEqual(0, weakKeyDictionary.Count);

            Exception exception = null;
            try
            {
                weakKeyDictionary.Remove(null);
            }
            catch (ArgumentNullException e)
            {
                exception = e;
            }
            Assert.IsNotNull(exception);

            exception = null;
            try
            {
                var i = weakKeyDictionary[new TestKey("1")];
            }
            catch (KeyNotFoundException e)
            {
                exception = e;
            }
            Assert.IsNotNull(exception);

            key = new TestKey("Yohan2");
            weakKeyDictionary.Add(key, 1);
            Assert.AreEqual(1, weakKeyDictionary[key]);

            weakKeyDictionary.Clear();
            Assert.AreEqual(0, weakKeyDictionary.Count);

            weakKeyDictionary.Add(key, 1);
            Assert.IsTrue(weakKeyDictionary.ContainsKey(key));
            Assert.IsTrue(weakKeyDictionary.ContainsValue(1));

            weakKeyDictionary[key] = 2;
            Assert.AreEqual(2, weakKeyDictionary[key]);

            bool contains = weakKeyDictionary.ContainsValue(2);
            Assert.IsTrue(contains);

            exception = null;
            try
            {
                weakKeyDictionary[null] = 3;
            }
            catch (ArgumentNullException e)
            {
                exception = e;
            }
            Assert.IsNotNull(exception);

            exception = null;
            try
            {
                weakKeyDictionary.Add(key, 1);
            }
            catch (ArgumentException e)
            {
                exception = e;
            }
            Assert.IsNotNull(exception);

            int value;
            weakKeyDictionary.TryGetValue(key, out value);
            Assert.AreEqual(2, value);

            var count = weakKeyDictionary.Count;
            key = null;
            GC.Collect();

            weakKeyDictionary.Add(new TestKey("yohan9"), 2);

            Assert.AreEqual(count, weakKeyDictionary.Keys.Count);
        }