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 whose 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With