Skip to content

Instantly share code, notes, and snippets.

@rezanid
Last active September 28, 2017 07:27
Show Gist options
  • Save rezanid/0cb2a7c46736fa99d7784974ac919237 to your computer and use it in GitHub Desktop.
Save rezanid/0cb2a7c46736fa99d7784974ac919237 to your computer and use it in GitHub Desktop.
Caching data in ASP.NET using Lazy<T>
class CachedDataSource
{
protected T RetrieveCachedData<T>(
string cacheKey, Func<T> fallbackFunction, CacheItemPolicy cachePolicy) where T : class
{
var originalData = new CacheItem<Lazy<T>>(new Lazy<T>(fallbackFunction));
var cachedData = (CacheItem<Lazy<T>>)_cacheProvider.AddOrGetExisting(cacheKey, originalData, cachePolicy);
if (cachedData != null)
{
Logger.LogMessage(SeverityLevels.Verbose,
CacheServiceLogCategory,
string.Format(DataReadFromCacheFormat, cacheKey, _regionName));
return cachedData.Item.Value;
}
Logger.LogMessage(SeverityLevels.Information,
CacheServiceLogCategory,
string.Format(DataAddedToCacheFormat, cacheKey, _regionName));
return originalData.Item.Value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment