Skip to content

Instantly share code, notes, and snippets.

@ChrisMcKee
Created January 4, 2013 12:14
Show Gist options
  • Select an option

  • Save ChrisMcKee/4452198 to your computer and use it in GitHub Desktop.

Select an option

Save ChrisMcKee/4452198 to your computer and use it in GitHub Desktop.
namespace Caching
{
using System;
using System.Collections.Generic;
using System.Web;
public static class CacheHelper
{
/// <summary>
/// Insert value into the cache using
/// appropriate name/value pairs
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="o">Item to be cached</param>
/// <param name="key">Name of item</param>
public static void Add<T>(T o, string key)
{
HttpRuntime.Cache.Insert(
key,
o,
null,
DateTime.Now.AddMinutes(1d),
System.Web.Caching.Cache.NoSlidingExpiration);
}
/// <summary>
/// Remove item from cache
/// </summary>
/// <param name="key">Name of cached item</param>
public static void Clear(string key)
{
HttpRuntime.Cache.Remove(key);
}
/// <summary>
/// Check for item in cache
/// </summary>
/// <param name="key">Name of cached item</param>
/// <returns></returns>
public static bool Exists(string key)
{
return HttpRuntime.Cache[key] != null;
}
/// <summary>
/// Retrieve cached item
/// </summary>
/// <typeparam name="T">Type of cached item</typeparam>
/// <param name="key">Name of cached item</param>
/// <param name="value">Cached value. Default(T) if
/// item doesn't exist.</param>
/// <returns>Cached item as type</returns>
public static bool Get<T>(string key, out T value)
{
try
{
if (!Exists(key))
{
value = default(T);
return false;
}
value = (T)HttpRuntime.Cache[key];
}
catch
{
value = default(T);
return false;
}
return true;
}
/// <summary>
/// Cache decorator
/// </summary>
public static class CacheProvider
{
public static Func<T, TResult> Decorate<T, TResult>(
Func<T, TResult> function)
{
var cache = new Dictionary<T, TResult>();
return (x) =>
{
if (!cache.ContainsKey(x))
{
cache.Add(x, function(x));
}
return cache[x];
};
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment