Expiring Cache in C#
Posted October 23, 2009 by Chris | Filed under .NET, C#
Ever need a simple cache that automatically expires items, removing them after a given time has elapsed? Well now you've got it: ExpiringValueCache and ExpiringObjectCache. ExpiringValueCache is used to store value types. ExpiringObjectCache is used to store reference types.
A background thread continuously runs, checking for expired items in a generic Dictionary. The size of the collection does not affect the productivity of this background expiration process. The scalability of the caches is the same as that of a generic Dictionary of the items that you're storing.
First, to create one of these expiring caches, pass in a TimeSpan for which items should live before being automatically removed. All objects in the cache use the same TimeSpan as thier lifespan. Here are caches with one-hour expirations:
var peopleCache = new ExpiringObjectCache(new TimeSpan(1, 0, 0));
var idCache = new ExpiringValueCache(new TimeSpan(1, 0, 0));
Next, to add an item to the cache, call its Add method. The first argument is the key for the item, and the second argument is the item.
peopleCache.Add("chris", people[0]);
idCache.Add("chris", people[0].Id);
To check for the existence of an item or retrieve it, use the cache collection's indexer. For ExpiringObjectCache, the object will be returned if the item exists; null if it's not or no longer (i.e. it expired) in the cache:
var chris = peopleCache["chris"]; if (chris == null) { // Not in cache. Expired? } else { // In cache, do something... }
Use ExpiringValueCache the same way—it also returns null if the item doesn't exist. It does this by wrapping the result in a System.Nullable:
var chrisId = idCache["chris"]; if (chrisId == null) { // Not in cache. Expired? } else { var id = chrisId.Value; }
Lastly, since the caches have a background thread expiring stale items, remember to Dispose() of the cache when you're done with it. The thread is a background thread, so it won't prevent the process from terminating, but you should always cleanly dispose of your resources.
That's it. Suitably simple, I hope.
November 26th, 2009 at 4:18 pm
Very nice; simular in ASP.NET-Cache.
Acutally i solve such problems with two dictionaries and doing an manual look-up if the objects are in an expired state.
Regards,
Marc