Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 970
Larsenal Avatar asked Sep 15 '11 18:09

Larsenal


1 Answers

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.

like image 85
BrokenGlass Avatar answered Oct 25 '22 01:10

BrokenGlass