包含过期项的哈希表
我想实现一个 HashTable
(或者可能是 HashSet
或 Dictionary
),它具有在一段时间后过期的唯一成员。例如:
// Items expire automatically after 10 seconds (Expiration period = 10 sec)
bool result = false;
// Starting from second 0
result = MyHashSet.Add("Bob"); // second 0 => true
result = MyHashSet.Add("Alice"); // second 5 => true
result = MyHashSet.Add("Bob"); // second 8 => false (item already exist)
result = MyHashSet.Add("Bob"); // second 12 => true (Bob has expired)
如何以最低成本以线程安全的方式做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以创建自己的哈希表,其中每个项目都包含创建时间和时间跨度。
在尝试返回值的索引器中,如果项目的生命周期已过期,则返回 null。并删除该项目。从表中删除项目的后台线程将无法确保您永远不会返回过期的项目。然后,您可以创建一个线程来执行此操作,以完全删除过期的项目,以在从未访问大量项目的情况下最大限度地减少内存消耗。
You could create you own Hash Table where each item contains a creation time and a timespan.
In the indexer where you try to return the value return null if the lifetime of the item has expired. And remove the item. A background thread that removes items from the table will not ensure you that you will never return an expired item without this. Then you can create a thread that does this just to remove expired items altogether to minimize memory consumption if a lot of items are never acessed.
您是否考虑过使用 System.Web.Caching 而不必自己动手?
http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx
编辑
好吧,上面的内容不会给系统增加太多的开销,但看看这个。
下面的代码有一些健康警告。
抛出新的 NotImplementedException()
。我会尝试过一会儿再回来讨论它,因为这是一个有趣的谜题。IDictionary、ICollection>、IEnumerable>、IDictionary、ICollection、IEnumerable、ISerializable、IDeserializationCallback
测试代码
实施
Have you considered using
System.Web.Caching
instead of having to roll your own ?http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx
EDIT
Well the above should not add THAT much of an overhead to the system but have a look at this.
A few health warnings on the code below.
throw new NotImplementedException()
s at the bottom. I'll try and come back to it in a while as it's an interesting puzzle.IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback
Test Code
Implementation
试试这个:
当然,List 可以替换为 Hashtable,并且(这会更正确)异步委托可以替换为 Timers,但我希望通用方法是明确的
try this:
of course, List can be replaced with Hashtable and (it would be even more correct) async delegates can be replaced with Timers, but I hope that common approach is clear