Skip to content

Instantly share code, notes, and snippets.

@abhilash0001
Created August 6, 2014 20:24
Show Gist options
  • Save abhilash0001/166b4da4a92b4b003ca7 to your computer and use it in GitHub Desktop.
Save abhilash0001/166b4da4a92b4b003ca7 to your computer and use it in GitHub Desktop.
Cache Helper - C#
using System;
using System.Configuration;
namespace Custom.Helpers.Common
{
public static class Cache
{
private const string CacheSetting = "Cache.Duration";
private static System.Web.Caching.Cache _cache { get { return System.Web.HttpContext.Current.Cache; } }
private static int _cacheDuration { get; set; }
static Cache()
{
_cacheDuration = GetCacheDuration();
}
public static void Set(string key, object value)
{
_cache.Insert(key, value,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
GetSlidingExpiration(_cacheDuration),
System.Web.Caching.CacheItemPriority.Default,
null);
}
public static T Get<T>(string key)
{
T value = default(T);
if (Exists(key))
value = (T)_cache.Get(key);
return value;
}
public static bool Exists(string key)
{
return _cache.Get(key) != null;
}
private static TimeSpan GetSlidingExpiration(int duration)
{
return new TimeSpan(0, duration, 0);
}
private static int GetCacheDuration()
{
//default
int duration = 10;
var setting = ConfigurationManager.AppSettings[CacheSetting];
if (!string.IsNullOrEmpty(setting))
int.TryParse(setting, out duration);
return duration;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment