C # list where items have TTL

For a simple example, I would like to have a list of strings. Each item in the list should “expire” 5 minutes after adding it to the list. Although it may not be a simple, built-in way to do this, I would like to get a data structure whose API seems to be "just working."

You can 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 the items will immediately lead to

 ["Bob", "Joe", "Tom", "Tim"] 

In a few minutes he should give

 ["Tom", "Tim"] 

In the end, the list should be empty.

+7
source share
2 answers

You can use the MemoryCache class in .NET 4, which allows you to specify TTL when adding an item.

A 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 

As long as you do not provide the TTL list directly, you can adapt it for your solution, you do not need to cache yourself.

+23
source

You should be able to use a SortedDictionary<DateTime, ...> and a custom IComparer<DateTime> , which "overrides" the dictionary order so that the first elements are first. Before returning items from a dictionary, simply delete the first N items that are too old.

Of course, changing the collection under the covers when the caller expects a simple read can lead to problems in a multi-threaded environment, but that's another topic ...

0
source

All Articles