/// <summary> /// 清空缓存中的所有对象。 /// </summary> public void Clear() { LruNormalNode <TKey, TValue> oldHead; lock (cacheLock) { cacheDict.Clear(); oldHead = head; head = null; count = 0; } if (IsDisposable) { // 释放对象资源。 LruNormalNode <TKey, TValue> node = oldHead; do { IDisposable disposable = node.Value as IDisposable; if (disposable != null) { disposable.Dispose(); } node = node.Next; } while (node != oldHead); } }
/// <summary> /// 将指定的链表节点移动到链表的头部。 /// </summary> /// <param name="node">要移动的链表节点。</param> private void MoveToFirst(LruNormalNode <TKey, TValue> node) { if (node != this.head) { Remove(node); AddFirst(node); } }
/// <summary> /// 将指定的节点添加到链表的头部。 /// </summary> /// <param name="node">要添加的节点。</param> private void AddFirst(LruNormalNode <TKey, TValue> node) { if (this.head == null) { node.Next = node.Previous = node; } else { node.Next = this.head; node.Previous = this.head.Previous; this.head.Previous.Next = node; this.head.Previous = node; } this.head = node; }
/// <summary> /// 从链表中移除指定的节点。 /// </summary> /// <param name="node">要移除的节点。</param> private void Remove(LruNormalNode <TKey, TValue> node) { if (node.Next == node) { this.head = null; } else { node.Next.Previous = node.Previous; node.Previous.Next = node.Next; if (this.head == node) { this.head = node.Next; } } }
/// <summary> /// 将指定的键和对象添加到缓存中,并返回添加的节点。 /// </summary> /// <param name="key">要添加的对象的键。</param> /// <param name="value">要添加的对象。</param> private void AddInternal(TKey key, TValue value) { LruNormalNode <TKey, TValue> node; IDisposable disposable = null; lock (cacheLock) { if (cacheDict.TryGetValue(key, out node)) { // 移动旧节点。 MoveToFirst(node); node.Value = value; } else { if (count >= maxSize) { // 淘汰旧节点。 node = this.head.Previous; cacheDict.Remove(node.Key); disposable = node.Value as IDisposable; Remove(node); node.Key = key; node.Value = value; } else { node = new LruNormalNode <TKey, TValue>(key, value); count++; } AddFirst(node); cacheDict.Add(key, node); } } if (disposable != null) { disposable.Dispose(); } }