Exemple #1
0
        /// <summary>
        /// Invalidates <see cref="Entry{TKey,Tvalue}"/> by provided key and deletes it from the set.
        /// </summary>
        /// <param name="key">Cache entry key to invalidate.</param>
        /// <param name="source">Value indicating the source of invalidation request.</param>
        /// <returns>Returns true if cache entry invalidation is successful,
        /// false if key is missing in cache set.</returns>
        internal bool InvalidateAndDelete(TKey key, InvalidationSource source)
        {
            lock (thisLock)
            {
                if (!cacheDictionary.ContainsKey(key))
                {
                    return(false);
                }

                cacheDictionary.Remove(key);
                EntryCount--;
                EvictionListener?.Invoke(
                    this,
                    new InvalidationEventArgs
                {
                    Source = source
                });

                return(true);
            }
        }
Exemple #2
0
        /// <summary>
        /// Insert key/value pair into cache set.
        /// </summary>
        /// <param name="key">Cache entry key.</param>
        /// <param name="value">Cache entry value.</param>
        internal void InsertEntry(TKey key, TValue value)
        {
            // we are locking the object to provide thread-safety.
            lock (thisLock)
            {
                // if key already exists in the cache set - replace the value.
                if (cacheDictionary.ContainsKey(key))
                {
                    EvictionListener?.Invoke(
                        this,
                        new InvalidationEventArgs
                    {
                        Source = InvalidationSource.Replacement
                    });
                    cacheDictionary[key] = new Entry <TKey, TValue>(key, value);
                    return;
                }

                // if cache set has more entries than n-Way parameter
                // we call the eviction algorithm
                if (EntryCount >= nWay)
                {
                    // selected entry is invalidated and the entry deletion procedure is being called.
                    if (!InvalidateAndDelete(
                            evictionAlgorithm.Evict(cacheDictionary.Values.ToList()).Key,
                            InvalidationSource.Eviction))
                    {
                        throw new ArgumentException("Eviction algorithm didn't provide valid entry to evict!");
                    }
                }

                // a new entry is then created and inserted into dictionary
                cacheDictionary.Add(key, new Entry <TKey, TValue>(key, value));

                EntryCount++;
            }
        }