Skip to content

Instantly share code, notes, and snippets.

@peteraritchie
Created January 18, 2012 15:15
Show Gist options
  • Save peteraritchie/1633459 to your computer and use it in GitHub Desktop.
Save peteraritchie/1633459 to your computer and use it in GitHub Desktop.
sample code
private T HandleItemCacheRetrieval<T>(string cacheKey, object cacheLock, Func<T> nonCachedMethod)
{
T retVal = default(T);
try
{
retVal = (T) Get(cacheKey);
}
catch (InvalidCastException ex) //it didn’t parse properly
{
LoggerManager.Error(ex);
}
if (retVal == null)
{
lock (cacheLock)
{
try
{
retVal = (T) Get(cacheKey); //make sure it’s still null (i.e. it didn’t get written while lock was being applied)
}
catch (InvalidCastException ex1) //it didn’t parse properly
{
LoggerManager.Error(ex1);
}
retVal = nonCachedMethod();
if (retVal != null)
{
Insert(cacheKey, retVal, _cacheLengthInSeconds);
}
}
}
return retVal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment