Last active
September 28, 2017 07:27
-
-
Save rezanid/0cb2a7c46736fa99d7784974ac919237 to your computer and use it in GitHub Desktop.
Caching data in ASP.NET using Lazy<T>
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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