/// <summary> /// Occurs when the item with the given key is used. /// </summary> /// <param name="key">Item key.</param> private void OnItemUsed(TKey key) { int itemIndex = -1; if (key != null) { lock (_lock) { itemIndex = Recency.IndexOf(key); if (itemIndex != 0) { Recency.RemoveAt(itemIndex); Recency.Insert(0, key); } } } }
/// <summary> /// Adds or updates the item with the given key. /// </summary> /// <param name="key">Item key.</param> /// <param name="value">Item value.</param> private void SetInternal(TKey key, TValue value) { bool hadItem = false; if (key != null) { hadItem = ContainsKey(key); if (!hadItem) { // Did we reach capacity? if (Count >= Capacity) { lock (_lock) { if (Count >= Capacity) { // Removing the oldest item RemoveInternal(Recency[Recency.Count - 1]); } } } } // Adding or updating the item Data.AddOrUpdate(key, value, (k, v) => value); if (!hadItem) { // Adding to recency Recency.Insert(0, key); } else { // Marking item as most recently used OnItemUsed(key); } } }