问题描述
我想实现一个的HashTable
(或mabybe一个 HashSet的
或词典
),它具有独特的成员,其中一段时间后到期。例如:
I want to implement a HashTable
(or mabybe a HashSet
or Dictionary
) which has unique members which expire after a while. For example:
// 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)
如何做,在以最低的成本线程安全的方式?
How to do that in a thread-safe manner with lowest costs?
推荐答案
您可以创建自己的哈希表,其中每个项目包含一个创建时间和时间跨度。
当你试图返回值返回NULL,如果该项目的生命周期已经过期的索引器。并删除该项目。后台线程从表中删除的项目将不能保证你,你永远没有这个返回一个过期的项目。然后,你可以创建一个线程,它只是为了完全删除过期的项目如果有很多项目都从未acessed以减少内存消耗。
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.
这篇关于用过期了项目哈希表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!