Skip to content

Instantly share code, notes, and snippets.

@HoraceBury
Created August 21, 2017 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HoraceBury/55277993ccde29b38bacf05bbdf17819 to your computer and use it in GitHub Desktop.
Save HoraceBury/55277993ccde29b38bacf05bbdf17819 to your computer and use it in GitHub Desktop.
Generic caching mechanism which makes sliding expiration easy.
using System;
using System.Collections.Generic;
using System.Runtime.Caching;
namespace CacheServices
{
public class Cache
{
protected MemoryCache _cache = new MemoryCache("general");
public static CacheItemPolicy DefaultPolicy { get; set; }
public static readonly Dictionary<string, CacheItemPolicy> Terms = new Dictionary<string, CacheItemPolicy>()
{
{"Short", new CacheItemPolicy {SlidingExpiration = new TimeSpan(0, 0, 30)}},
{"Medium", new CacheItemPolicy {SlidingExpiration = new TimeSpan(0, 5, 0)}},
{"Long", new CacheItemPolicy {SlidingExpiration = new TimeSpan(1, 0, 0)}},
{"Always", new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.MaxValue}}
};
static Cache()
{
DefaultPolicy = Terms["Short"];
}
public object this[string key]
{
get { return Get(key); }
set { Add(key, value, DefaultPolicy); }
}
public void Add(string key, object item, CacheItemPolicy term)
{
if (item == null)
Remove(key);
else
{
_cache.Remove(key);
_cache.Add(key, item, term);
}
}
public object Get(string key)
{
return _cache.Get(key);
}
public object Remove(string key)
{
return _cache.Remove(key);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment