字典与项目限制

我需要提供对跨会话的所有用户持久存储的键/值对存储的访问。

我可以轻松地为此创建单例,但出于性能原因,我想将字典的大小限制为10000个项目(或任何高性能数字,因为对象将无限期地持续存在)

是否有一种字典forms,我可以指定存储对象数量的限制,当超过该限制时,删除最旧的条目?

没有这样的内置字典,但你可以建立自己的字典。 您将需要一个密钥队列 – 这将允许您快速查找最旧的条目并将其删除。 此外,您还需要一个简单的字典来保存您的值 – 这样您就可以快速搜索它们:

 public class SuperDictionary { private Dictionary dictionary; private Queue keys; private int capacity; public SuperDictionary(int capacity) { this.keys = new Queue(capacity); this.capacity = capacity; this.dictionary = new Dictionary(capacity); } public void Add(TKey key, TValue value) { if (dictionary.Count == capacity) { var oldestKey = keys.Dequeue(); dictionary.Remove(oldestKey); } dictionary.Add(key, value); keys.Enqueue(key); } public TValue this[TKey key] { get { return dictionary[key]; } } } 

注意:您可以实现IDictionary接口,使此类成为“真正的”字典。

使用Cache ,而不是Session 。 它不是特定于用户的,您可以设置缓存的最大大小。 添加新项目并且缓存已满时,它将删除项目以腾出空间。 它允许复杂的老化机制,例如在固定的时间段之后移除的项目,在其最后使用之后的固定时间段,优先级(在决定移除什么时要考虑)等。

不,没有内置字典可以做到这一点。 实际上,所有通用集合都是无限大小的。

但是,您可以轻松地创建Queue>以及一个检查计数并在添加元素并且长度太长时执行出队的函数。 Dictionary在这里是一个困难的选择,因为没有办法确定“年龄”(除非你把它作为键或值的一部分)。

就像是:

 public void AddDataToDictionary(string key, int value) { if (queue.Count > 10000) queue.Dequeue(); queue.Enqueue(new KeyValuePair(key, value); } 

这是一个字典实现,具有以下删除策略:

 EmptyRemovalStrategy – Removes the first item in it's internal collection. Does not track access in any way. MruRemovalStrategy – Removes the most recently used (most accessed) item in the CacheDictionary. LruRemovalStrategy – Removes the least recently used (least accessed) item in the CacheDictionary. 

CacheDictionary是一个包含有限数量项的字典。 因此,您可以指定最大大小为1000.通过此实现,您还可以确定条目的“年龄”并删除最少使用的(因此缓存)

http://alookonthecode.blogspot.com/2012/03/implementing-cachedictionarya.html