Skip to content

Instantly share code, notes, and snippets.

@bryan-c-oconnell
Created July 24, 2017 20:45
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 bryan-c-oconnell/839216873ed992b1c03a9a9b43af11c5 to your computer and use it in GitHub Desktop.
Save bryan-c-oconnell/839216873ed992b1c03a9a9b43af11c5 to your computer and use it in GitHub Desktop.
SimpleCache
using System;
using System.Runtime.Caching;
namespace BOC.Samples.Caching
{
/// <summary>A simple wrapper for the .NET memory cache.</summary>
/// <remarks>Samples to create this class were taken from the following posts:
/// - http://www.allinsight.de/caching-objects-in-net-with-memorycache/
/// - http://www.codeproject.com/Articles/756423/How-to-Cache-Objects-Simply-using-System-Runtime-C
/// </remarks>
public static class SampleDataCache
{
private static MemoryCache _cache = new MemoryCache("cache-name-here");
private static readonly object cacheLocker = new object();
/// <summary></summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <remarks>NOTE: Items added are set to automatically expire after 1 hour.</remarks>
public static void AddItem(string key, object value)
{
lock (cacheLocker)
{
var expirationPolicy = new CacheItemPolicy();
expirationPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(1);
_cache.Add(key, value, expirationPolicy);
}
}
/// <summary></summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="minutesToHold">Tell the cache how long to hang onto the data.</param>
public static void AddItem(string key, object value, double minutesToHold)
{
lock (cacheLocker)
{
var expirationPolicy = new CacheItemPolicy();
expirationPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutesToHold);
_cache.Add(key, value, expirationPolicy);
}
}
/// <summary></summary>
/// <param name="key"></param>
public static object FetchItem(string key)
{
lock (cacheLocker)
{
return _cache.Get(key);
}
}
/// <summary></summary>
/// <param name="key"></param>
public static void DeleteItem(string key)
{
lock (cacheLocker)
{
_cache.Remove(key);
}
}
/// <summary></summary>
public static int ItemCount()
{
lock (cacheLocker)
{
return (int)_cache.GetCount();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment