Esempio n. 1
0
        /// <summary>
        /// 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.
        /// </summary>
        public void RemoveCollectedEntries()
        {
            List <object> entriesToBeRemoved = new List <object>();

            foreach (var key in this.dictionary.Keys)
            {
                WeakKeyReference <TKey> weakKey = key as WeakKeyReference <TKey>;
                if (weakKey != null)
                {
                    if (!weakKey.IsAlive)
                    {
                        entriesToBeRemoved.Add(key);
                    }
                }
                else if (this.RemoveCollectedEntriesRules.Any(f => f(key)))
                {
                    entriesToBeRemoved.Add(key);
                }
            }

            foreach (var key in entriesToBeRemoved)
            {
                if (this.dictionary.Remove(key))
                {
                    this.countForRefresh--;
                }
            }

            // After a clean, we will let the dict to clean itself after adding the next intervalForRefresh(1000) items.
            this.countLimitForRefresh = this.countForRefresh + intervalForRefresh;
        }
Esempio n. 2
0
        /// <summary>
        /// Get the hash code for the specified object.
        /// </summary>
        /// <param name="obj">The object for which a hash code is to be returned.</param>
        /// <returns>
        /// A hash code for the specified object.
        /// </returns>
        public virtual int GetHashCode(object obj)
        {
            WeakKeyReference <T> weakKey = obj as WeakKeyReference <T>;

            if (weakKey != null)
            {
                return(weakKey.HashCode);
            }

            return(this.comparer.GetHashCode((T)obj));
        }
Esempio n. 3
0
        /// <summary>
        /// Gets the target of the input object if it is a <see cref="WeakKeyReference&lt;T&gt;"/>, else return it self.
        /// </summary>
        /// <param name="obj">The input object from which to get the target.</param>
        /// <param name="isDead">Indicate whether the object is dead if it is a <see cref="WeakKeyReference&lt;T&gt;"/>.</param>
        /// <returns>The target of the input object.</returns>
        protected virtual T GetTarget(object obj, out bool isDead)
        {
            T target;

            WeakKeyReference <T> wref = obj as WeakKeyReference <T>;

            if (wref != null)
            {
                target = wref.Target;
                isDead = !wref.IsAlive;
            }
            else
            {
                target = (T)obj;
                isDead = false;
            }

            return(target);
        }