private static void AddCollectableItems(WeakValueDictionary <int, object> c, int startKey, int count)
 {
     for (int i = 0; i < count; i++)
     {
         c.Add(startKey++, new object());
     }
 }
        public void ScavengeOnGrow()
        {
            var dictionary = new WeakValueDictionary <object, object>();

            for (int i = 0; i < 100; i++)
            {
                dictionary[new Object()] = new Object();

                // Randomly collect some
                if (i == 15)
                {
                    GC.Collect();
                }
            }

            // We should have scavenged at least once
            Console.WriteLine("Count {0}", dictionary.Count);
            Assertion.AssertEquals(true, dictionary.Count < 100);

            // Finish with explicit scavenge
            int count1  = dictionary.Count;
            int removed = dictionary.Scavenge();
            int count2  = dictionary.Count;

            Console.WriteLine("Removed {0}", removed);
            Assertion.AssertEquals(removed, count1 - count2);
        }
Esempio n. 3
0
 private void AssertEnumeration(WeakValueDictionary <int, Item> dict, int key)
 {
     foreach (var kvp in dict)
     {
         Assert.That(kvp.Key, Is.Not.EqualTo(key));
     }
 }
Esempio n. 4
0
        public void When_element_is_added_twice_with_the_same_key_Then_exception_is_thrown()
        {
            var dict = new WeakValueDictionary <int, Item> {
                { 0, new Item() }
            };

            Assert.Throws <ArgumentException>(() => dict.Add(0, new Item()));
        }
        /// <summary>
        /// Creates an empty cache.
        /// </summary>
        internal ProjectRootElementCache(bool autoReloadFromDisk)
        {
            DebugTraceCache("Constructing with autoreload from disk: ", autoReloadFromDisk);

            _weakCache          = new WeakValueDictionary <string, ProjectRootElement>(StringComparer.OrdinalIgnoreCase);
            _strongCache        = new LinkedList <ProjectRootElement>();
            _autoReloadFromDisk = autoReloadFromDisk;
        }
Esempio n. 6
0
        public void When_dictionary_is_cleared_Then_it_is_empty()
        {
            var dict = new WeakValueDictionary <int, Item> {
                [0] = null,
                [1] = new Item()
            };

            dict.Clear();

            Assert.That(dict.Count, Is.Zero);
        }
        public void TryGetValue_ReferenceNotFound()
        {
            var dictionary = new WeakValueDictionary <string, string>();

            string v;
            bool   result = dictionary.TryGetValue("x", out v);

            Assert.IsFalse(result);
            Assert.IsNull(v);
            Assert.IsFalse(dictionary.Contains("x"));
        }
Esempio n. 8
0
        public void When_null_item_is_added_Then_its_key_exists()
        {
            var dict = new WeakValueDictionary <int, Item>();

            dict[1] = null;
            Item item;
            bool exists = dict.TryGetValue(1, out item);

            Assert.That(dict.Count, Is.EqualTo(1));
            Assert.That(exists, Is.True);
            Assert.That(item, Is.Null);
        }
Esempio n. 9
0
        public void When_item_is_added_Then_it_can_be_retrieved()
        {
            var  dict = new WeakValueDictionary <int, Item>();
            Item item = new Item();

            dict[1] = item;
            bool exists = dict.TryGetValue(1, out item);

            Assert.That(dict.Count, Is.EqualTo(1));
            Assert.That(exists, Is.True);
            Assert.That(item, Is.EqualTo(item));
        }
Esempio n. 10
0
        public void When_element_is_set_twice_with_for_the_same_key_Then_key_value_is_changed()
        {
            var dict  = new WeakValueDictionary <int, Item>();
            var item  = new Item();
            var item2 = new Item();

            dict[0] = item;
            dict[0] = item2;

            Assert.That(dict.Count, Is.EqualTo(1));
            Assert.That(dict[0], Is.EqualTo(item2));
        }
Esempio n. 11
0
        public void When_key_is_removed_Then_count_is_decreased()
        {
            var dict = new WeakValueDictionary <int, Item> {
                [0] = new Item(),
                [1] = new Item()
            };

            bool removed = dict.Remove(0);

            Assert.That(removed, Is.True);
            Assert.That(dict.Count, Is.EqualTo(1));
        }
Esempio n. 12
0
        public void When_non_existing_key_is_removed_Then_false_is_returned()
        {
            var dict = new WeakValueDictionary <int, Item> {
                [0] = new Item(),
                [1] = new Item()
            };

            bool removed = dict.Remove(3);

            Assert.That(removed, Is.False);
            Assert.That(dict.Count, Is.EqualTo(2));
        }
Esempio n. 13
0
        public void When_item_is_added_Then_it_can_be_garbage_collected()
        {
            var dict = new WeakValueDictionary <int, Item> {
                [1] = new Item()
            };

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

            AssertEnumeration(dict, 1);
            Assert.That(dict.ContainsKey(1), Is.False);
            Assert.That(dict.Count, Is.EqualTo(0));
        }
Esempio n. 14
0
        public void When_getting_keys_collection_Then_actual_dictionary_keys_are_returned()
        {
            var dict = new WeakValueDictionary <int, Item> {
                [0] = new Item(),
                [1] = new Item(),
                [2] = new Item()
            };

            var keys = dict.Keys;

            Assert.That(keys.Count, Is.EqualTo(3));
            Assert.That(keys, Is.EqualTo(new[] { 0, 1, 2 }));
        }
Esempio n. 15
0
 protected internal SymbolPool(int firstID, bool useStrongRefs, int poolId)
 {
     if (useStrongRefs)
     {
         _map = new Dictionary <string, Symbol>();
     }
     else
     {
         _map = _weakMap = new WeakValueDictionary <string, Symbol>();
     }
     _nextId = firstID;
     _poolId = poolId;
 }
        public void SpecifiedEqualityComparer()
        {
            string k1 = "key";
            string v1 = "value";

            var dictionary = new WeakValueDictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            dictionary[k1] = v1;

            string v2 = dictionary["KEY"];

            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));
        }
Esempio n. 17
0
        /// <summary>
        /// Clears out the cache.
        /// Called when all projects are unloaded and possibly when a build is done.
        /// </summary>
        internal void Clear()
        {
            lock (_locker)
            {
                LinkedList <ProjectRootElement> oldStrongCache = _strongCache;
                _weakCache   = new WeakValueDictionary <string, ProjectRootElement>(StringComparer.OrdinalIgnoreCase);
                _strongCache = new LinkedList <ProjectRootElement>();

                foreach (ProjectRootElement projectRootElement in oldStrongCache)
                {
                    RaiseProjectRootElementRemovedFromStrongCache(projectRootElement);
                }
            }
        }
        public void Indexer_ReferenceFound()
        {
            string k1 = "key";
            string v1 = "value";

            var dictionary = new WeakValueDictionary<string, string>();
            dictionary[k1] = v1;

            // Now look for the same key we inserted
            string v2 = dictionary[k1];

            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));
            Assertion.AssertEquals(true, dictionary.Contains(k1));
        }
Esempio n. 19
0
        public void When_getting_values_collection_Then_actual_dictionary_values_without_nulls_are_returned()
        {
            var item  = new Item();
            var item2 = new Item();
            var dict  = new WeakValueDictionary <int, Item> {
                [0] = item,
                [1] = null,
                [2] = item2
            };

            var values = dict.Values;

            Assert.That(values.Count, Is.EqualTo(2));
            Assert.That(values, Is.EqualTo(new[] { item, item2 }));
        }
        public void Indexer_ReferenceFound()
        {
            string k1 = "key";
            string v1 = "value";

            var dictionary = new WeakValueDictionary <string, string>();

            dictionary[k1] = v1;

            // Now look for the same key we inserted
            string v2 = dictionary[k1];

            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));
            Assertion.AssertEquals(true, dictionary.Contains(k1));
        }
        public void TryGetValue_ReferenceFound()
        {
            string k1 = "key";
            string v1 = "value";

            var dictionary = new WeakValueDictionary <string, string>();

            dictionary[k1] = v1;

            // Now look for the same key we inserted
            string v2;
            bool   result = dictionary.TryGetValue(k1, out v2);

            Assertion.AssertEquals(true, result);
            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));
        }
        public void ExplicitScavenge()
        {
            object k1 = new object();
            object v1 = new object();

            var dictionary = new WeakValueDictionary <object, object>();

            dictionary[k1] = v1;

            Assertion.AssertEquals(1, dictionary.Count);

            v1 = null;
            GC.Collect();

            dictionary.Scavenge();

            Assertion.AssertEquals(0, dictionary.Count);
        }
        public void Indexer_NullValue_ReferenceFound()
        {
            string k1 = "key";
            string v1 = null;

            var dictionary = new WeakValueDictionary<string, string>();
            dictionary[k1] = v1;

            // Now look for the same key we inserted
            string v2 = dictionary[k1];

            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));
            Assertion.AssertEquals(true, dictionary.Contains(k1));

            // Should not scavenge values that are null, rather than collected
            dictionary.Scavenge();
            Assertion.AssertEquals(1, dictionary.Count);
        }
        public void EnumerationCleaning()
        {
            var    c = new WeakValueDictionary <int, object>();
            object x = new object();

            using (NoGCRegion.Enter(1000)) {
                c.Add(0, x);
                c.Add(1, x);
                c.Add(2, x);

                AddCollectableItems(c, 3, 3);

                Assert.AreEqual(6, c.AddCountSinceLastClean);
                Assert.AreEqual(6, c.UnsafeCount);
                Assert.IsTrue(c.ContainsKey(1));

                #if DEBUG || !NETFRAMEWORK // Causes entry with key 4 not to collection on NETFW release builds
                Assert.IsTrue(c.ContainsKey(4));
                #endif
            }

            Helpers.CollectAndWait();

            Assert.IsTrue(c.ContainsKey(1));
            Assert.IsFalse(c.ContainsKey(4));

            foreach (object o in c)
            {
            }

            Assert.IsTrue(c.Remove(0));
            Assert.IsTrue(c.Remove(1));
            Assert.IsFalse(c.Remove(4));

            #if NETCOREAPP2_2 // NS2.0 target does not support removing stale entries as items are encountered.
            Assert.AreEqual(6, c.AddCountSinceLastClean);
            Assert.AreEqual(4, c.UnsafeCount);
            #else
            Assert.AreEqual(0, c.AddCountSinceLastClean);
            Assert.AreEqual(1, c.UnsafeCount);
            #endif

            GC.KeepAlive(x);
        }
        public void Indexer_NullValue_ReferenceFound()
        {
            string k1 = "key";
            string v1 = null;

            var dictionary = new WeakValueDictionary <string, string>();

            dictionary[k1] = v1;

            // Now look for the same key we inserted
            string v2 = dictionary[k1];

            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));
            Assertion.AssertEquals(true, dictionary.Contains(k1));

            // Should not scavenge values that are null, rather than collected
            dictionary.Scavenge();
            Assertion.AssertEquals(1, dictionary.Count);
        }
        public void EqualityComparer()
        {
            string k1 = "key";
            string v1 = "value";

            var dictionary = new WeakValueDictionary <string, string>();

            dictionary[k1] = v1;

            // Now look for a different but equatable key
            // Don't create it with a literal or the compiler will intern it!
            string k2 = String.Concat("k", "ey");

            Assert.IsFalse(Object.ReferenceEquals(k1, k2));

            string v2 = dictionary[k2];

            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));
        }
Esempio n. 27
0
        public void When_dictionary_is_serialized_to_xml_Then_valid_xml_is_returned()
        {
            var dict = new WeakValueDictionary <int, Item>();

            dict[0] = null;
            dict[1] = new Item {
                Value = 1
            };
            string resultingXml;
            var    serializer = new DataContractSerializer(typeof(WeakValueDictionary <int, Item>), new[] { typeof(Item) });

            using (var memStream = new MemoryStream())
                using (var reader = new StreamReader(memStream)) {
                    serializer.WriteObject(memStream, dict);
                    memStream.Seek(0, SeekOrigin.Begin);
                    resultingXml = reader.ReadToEnd();
                }

            Assert.That(resultingXml, Is.EqualTo(Xml));
        }
        public void TryGetNullValue_ReferenceFound()
        {
            string k1 = "key";
            string v1 = null;

            var dictionary = new WeakValueDictionary <string, string>();

            dictionary[k1] = v1;

            // Now look for the same key we inserted
            string v2;
            bool   result = dictionary.TryGetValue(k1, out v2);

            Assertion.AssertEquals(true, result);
            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));

            // Should not scavenge values that are null, rather than collected
            dictionary.Scavenge();
            Assertion.AssertEquals(1, dictionary.Count);
        }
        public void OnlyValuesCollectable()
        {
            long memory0 = GC.GetTotalMemory(true);

            string k1 = new string('k', BigMemoryFootprintTest);
            string v1 = new string('v', BigMemoryFootprintTest);

            // Each character is 2 bytes, so about 4MB of this should be the strings
            long memory1 = GC.GetTotalMemory(true);

            var dictionary = new WeakValueDictionary <string, string>();

            dictionary[k1] = v1;

            k1 = null;

            long memory2 = GC.GetTotalMemory(true);

            // Key not collected, should be about the same
            long difference = memory1 - memory2;

            Console.WriteLine("Before {0} Start {1}, end {2}, diff {3}, {4} more than start", memory0, memory1, memory2, difference, memory2 - memory0);
            Assertion.AssertEquals(true, difference < 500000); // big noise allowance

            v1 = null;

            memory2 = GC.GetTotalMemory(true);

            // Value collected, should be about 2MB less
            difference = memory1 - memory2;

            Console.WriteLine("Before {0} Start {1}, end {2}, diff {3}, {4} more than start", memory0, memory1, memory2, difference, memory2 - memory0);
            Assertion.AssertEquals(true, difference > 1500000); // 2MB minus big noise allowance

            // This line is VERY important, as it keeps the GC from being too smart and collecting
            // the dictionary and its large strings because we never use them again.
            GC.KeepAlive(dictionary);
        }
Esempio n. 30
0
        /// <summary>
        /// Discard any entries (weak and strong) which do not have the explicitlyLoaded flag set.
        /// </summary>
        internal void DiscardImplicitReferences()
        {
            lock (_locker)
            {
                // Make a new Weak cache only with items that have been explicitly loaded, this will be a small number, there will most likely
                // be many items which were not explicitly loaded (ie p2p references).
                WeakValueDictionary <string, ProjectRootElement> oldWeakCache = _weakCache;
                _weakCache = new WeakValueDictionary <string, ProjectRootElement>(StringComparer.OrdinalIgnoreCase);

                LinkedList <ProjectRootElement> oldStrongCache = _strongCache;
                _strongCache = new LinkedList <ProjectRootElement>();

                foreach (string projectPath in oldWeakCache.Keys)
                {
                    ProjectRootElement rootElement;

                    if (oldWeakCache.TryGetValue(projectPath, out rootElement))
                    {
                        if (rootElement.IsExplicitlyLoaded)
                        {
                            _weakCache[projectPath] = rootElement;
                        }

                        if (rootElement.IsExplicitlyLoaded && oldStrongCache.Contains(rootElement))
                        {
                            _strongCache.AddFirst(rootElement);
                        }
                        else
                        {
                            _strongCache.Remove(rootElement);
                            RaiseProjectRootElementRemovedFromStrongCache(rootElement);
                        }
                    }
                }
            }
        }
        public void Clean()
        {
            var    c = new WeakValueDictionary <int, object>();
            object x = new object();

            using (NoGCRegion.Enter(1000)) {
                c.Add(0, x);
                c.Add(1, x);
                c.Add(2, x);

                AddCollectableItems(c, 3, 3);

                Assert.AreEqual(6, c.AddCountSinceLastClean);
                Assert.AreEqual(6, c.UnsafeCount);
            }

            Helpers.CollectAndWait();

            c.Clean();
            Assert.AreEqual(0, c.AddCountSinceLastClean);
            Assert.AreEqual(3, c.UnsafeCount);

            GC.KeepAlive(x);
        }
Esempio n. 32
0
        /// <summary>
        /// Creates an empty cache.
        /// </summary>
        internal ProjectRootElementCache(bool autoReloadFromDisk)
        {
            DebugTraceCache("Constructing with autoreload from disk: ", autoReloadFromDisk);

            _weakCache = new WeakValueDictionary<string, ProjectRootElement>(StringComparer.OrdinalIgnoreCase);
            _strongCache = new LinkedList<ProjectRootElement>();
            _autoReloadFromDisk = autoReloadFromDisk;
        }
        public void ScavengeOnGrow()
        {
            var dictionary = new WeakValueDictionary<object, object>();

            for (int i = 0; i < 100; i++)
            {
                dictionary[new Object()] = new Object();

                // Randomly collect some
                if (i == 15)
                {
                    GC.Collect();
                }
            }

            // We should have scavenged at least once
            Console.WriteLine("Count {0}", dictionary.Count);
            Assertion.AssertEquals(true, dictionary.Count < 100);

            // Finish with explicit scavenge
            int count1 = dictionary.Count;
            int removed = dictionary.Scavenge();
            int count2 = dictionary.Count;

            Console.WriteLine("Removed {0}", removed);
            Assertion.AssertEquals(removed, count1 - count2);
        }
 public void Indexer_NotFound()
 {
     var    dictionary = new WeakValueDictionary <string, string>();
     string value      = dictionary["x"];
 }
        public void EqualityComparer()
        {
            string k1 = "key";
            string v1 = "value";

            var dictionary = new WeakValueDictionary<string, string>();
            dictionary[k1] = v1;

            // Now look for a different but equatable key
            // Don't create it with a literal or the compiler will intern it!
            string k2 = String.Concat("k", "ey");

            Assert.IsFalse(Object.ReferenceEquals(k1, k2));

            string v2 = dictionary[k2];

            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));
        }
        public void OnlyValuesCollectable()
        {
            long memory0 = GC.GetTotalMemory(true);

            string k1 = new string('k', BigMemoryFootprintTest);
            string v1 = new string('v', BigMemoryFootprintTest);

            // Each character is 2 bytes, so about 4MB of this should be the strings
            long memory1 = GC.GetTotalMemory(true);

            var dictionary = new WeakValueDictionary<string, string>();
            dictionary[k1] = v1;

            k1 = null;

            long memory2 = GC.GetTotalMemory(true);

            // Key not collected, should be about the same 
            long difference = memory1 - memory2;

            Console.WriteLine("Before {0} Start {1}, end {2}, diff {3}, {4} more than start", memory0, memory1, memory2, difference, memory2 - memory0);
            Assertion.AssertEquals(true, difference < 500000); // big noise allowance

            v1 = null;

            memory2 = GC.GetTotalMemory(true);

            // Value collected, should be about 2MB less
            difference = memory1 - memory2;

            Console.WriteLine("Before {0} Start {1}, end {2}, diff {3}, {4} more than start", memory0, memory1, memory2, difference, memory2 - memory0); 
            Assertion.AssertEquals(true, difference > 1500000); // 2MB minus big noise allowance

            // This line is VERY important, as it keeps the GC from being too smart and collecting
            // the dictionary and its large strings because we never use them again.  
            GC.KeepAlive(dictionary);
        }
        public void ExplicitScavenge()
        {
            object k1 = new object();
            object v1 = new object();

            var dictionary = new WeakValueDictionary<object, object>();
            dictionary[k1] = v1;

            Assertion.AssertEquals(1, dictionary.Count);

            v1 = null;
            GC.Collect();

            dictionary.Scavenge();

            Assertion.AssertEquals(0, dictionary.Count);
        }
Esempio n. 38
0
        /// <summary>
        /// Clears out the cache.
        /// Called when all projects are unloaded and possibly when a build is done.
        /// </summary>
        internal void Clear()
        {
            lock (_locker)
            {
                LinkedList<ProjectRootElement> oldStrongCache = _strongCache;
                _weakCache = new WeakValueDictionary<string, ProjectRootElement>(StringComparer.OrdinalIgnoreCase);
                _strongCache = new LinkedList<ProjectRootElement>();

                foreach (ProjectRootElement projectRootElement in oldStrongCache)
                {
                    RaiseProjectRootElementRemovedFromStrongCache(projectRootElement);
                }
            }
        }
Esempio n. 39
0
        /// <summary>
        /// Discard any entries (weak and strong) which do not have the explicitlyLoaded flag set.
        /// </summary>
        internal void DiscardImplicitReferences()
        {
            lock (_locker)
            {
                // Make a new Weak cache only with items that have been explicitly loaded, this will be a small number, there will most likely 
                // be many items which were not explicitly loaded (ie p2p references).
                WeakValueDictionary<string, ProjectRootElement> oldWeakCache = _weakCache;
                _weakCache = new WeakValueDictionary<string, ProjectRootElement>(StringComparer.OrdinalIgnoreCase);

                LinkedList<ProjectRootElement> oldStrongCache = _strongCache;
                _strongCache = new LinkedList<ProjectRootElement>();

                foreach (string projectPath in oldWeakCache.Keys)
                {
                    ProjectRootElement rootElement;

                    if (oldWeakCache.TryGetValue(projectPath, out rootElement))
                    {
                        if (rootElement.IsExplicitlyLoaded)
                        {
                            _weakCache[projectPath] = rootElement;
                        }

                        if (rootElement.IsExplicitlyLoaded && oldStrongCache.Contains(rootElement))
                        {
                            _strongCache.AddFirst(rootElement);
                        }
                        else
                        {
                            _strongCache.Remove(rootElement);
                            RaiseProjectRootElementRemovedFromStrongCache(rootElement);
                        }
                    }
                }
            }
        }
 public void Indexer_NotFound()
 {
     var dictionary = new WeakValueDictionary<string, string>();
     string value = dictionary["x"];
 }
        public void TryGetValue_ReferenceFound()
        {
            string k1 = "key";
            string v1 = "value";

            var dictionary = new WeakValueDictionary<string, string>();
            dictionary[k1] = v1;

            // Now look for the same key we inserted
            string v2;
            bool result = dictionary.TryGetValue(k1, out v2);

            Assertion.AssertEquals(true, result);
            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));
        }
        public void SpecifiedEqualityComparer()
        {
            string k1 = "key";
            string v1 = "value";

            var dictionary = new WeakValueDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            dictionary[k1] = v1;

            string v2 = dictionary["KEY"];

            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));
        }
        public void TryGetNullValue_ReferenceFound()
        {
            string k1 = "key";
            string v1 = null;

            var dictionary = new WeakValueDictionary<string, string>();
            dictionary[k1] = v1;

            // Now look for the same key we inserted
            string v2;
            bool result = dictionary.TryGetValue(k1, out v2);

            Assertion.AssertEquals(true, result);
            Assertion.AssertEquals(true, Object.ReferenceEquals(v1, v2));

            // Should not scavenge values that are null, rather than collected
            dictionary.Scavenge();
            Assertion.AssertEquals(1, dictionary.Count);
        }
        public void TryGetValue_ReferenceNotFound()
        {
            var dictionary = new WeakValueDictionary<string, string>();

            string v;
            bool result = dictionary.TryGetValue("x", out v);

            Assert.IsFalse(result);
            Assert.IsNull(v);
            Assert.IsFalse(dictionary.Contains("x"));
        }