Time-based Dictionary/Hashtable with 128-bit keys, i.e. timeout a value out of the dictionary

江枫思渺然 提交于 2019-12-06 06:51:43

You can eliminate having to scan the entire collection periodically by using a priority queue (or just a min heap) and an associated dictionary. Unfortunately, the .NET Framework doesn't include a priority queue collection, but there are some available. I published a simple binary heap a while back.

The idea here is that when you add an item, you add it to the dictionary and to the heap. If you want to look up an item by its key, you look it up in the dictionary. If you want to remove the first item from the heap, you get it from the heap and, using the key (which is part of the data), remove it from the dictionary.

The beauty is that, rather than having to scan the entire dictionary to determine which ones need to be removed, you can peek at the top of the heap:

while (heap.Count > 0 && heap.Peek().ExpirationTime < time)
{
    var item = heap.RemoveRoot();
    dictionary.Remove(item.Key);
}

The primary drawback to this approach is that it takes a bit more memory because you have the overhead of the dictionary entries.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!