C# list where items have a TTL
For sake of a simple example, I'd like to have a list of strings. Each item in the list should "expire" 5 minutes after adding it to the list. Although there may not be an easy, built-in way to do this, I'd like to end up with a data structure who开发者_如何学Cse API feels like it "just works".
You might use it as follows:
var now = DateTime.now();
var list = new ListWithTTL<string>();
list.add("Bob", now);
list.add("Joe", now.AddMinutes(1));
list.add("Tom", now.AddMinutes(2));
list.add("Tim", now.AddMinutes(2));
Inspecting elements immediately would yield
["Bob", "Joe", "Tom", "Tim"]
A few minutes later it should yield
["Tom", "Tim"]
Eventually the list should be empty.
You could use the MemoryCache
class in .NET 4 which allows you to specify a TTL when you add an item.
Simple example:
MemoryCache cache = new MemoryCache("foo");
cache.Add("bar", "baz", DateTime.Now.AddSeconds(5));
var bar = cache["bar"];//returns "baz"
Thread.Sleep(TimeSpan.FromSeconds(6));
var expired = cache["bar"]; //returns null
While not providing you directly with a TTL list you could adapt this for your solution, no need to implement cache expiration yourself.
You should be able to use SortedDictionary<DateTime, ...>
and a custom IComparer<DateTime>
that "reverses" the order of the dictionary so the oldest elements come first. Before returning elements from the dictionary, simply remove first N elements that are too old.
Of course, modifying collection "under the covers" when caller is expecting a simple read may lead to problems in multi-threaded environment, but this is a different topic...
精彩评论