Skip to content

Instantly share code, notes, and snippets.

@jbubriski
Forked from codeimpossible/gist:3207268
Created July 30, 2012 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jbubriski/3207278 to your computer and use it in GitHub Desktop.
Save jbubriski/3207278 to your computer and use it in GitHub Desktop.
Cache locking with timeout.
private static readonly string _languagesKey = "languages";
public static Dictionary<string, string> GetLanguages()
{
return GetData(_languagesKey, 15, () =>
{
// TODO: Get data from language service
var languages = new Dictionary<string, string>();
return languages;
});
}
public static T GetData<T>(string dataCacheKey, int cacheTimeInMinutes, Func<T> dataMethod) where T : class
{
var data = (T)HttpRuntime.Cache.Get(dataCacheKey);
if (data == null)
{
lock (HttpRuntime.Cache)
{
data = (T)HttpRuntime.Cache.Get(dataCacheKey);
if (data == null)
{
data = dataMethod();
HttpRuntime.Cache.Add(dataCacheKey, data, null, DateTime.Now.AddMinutes(cacheTimeInMinutes), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
}
}
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment