static public class CachedData
{
const int DEFAULT_CACHE_TIME_SECONDS = 60;
// helper method
static private T Get<T>(string key, Func<T> retriever, int cachedTimeInSeconds) where T : class
{
var cacheItem = MemoryCache.Default.GetCacheItem(key);
if (cacheItem == null)
{
T data = retriever();
MemoryCache.Default.Set(key, data, new CacheItemPolicy()
{
AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(cachedTimeInSeconds)
});
return data;
}
else
{
return (cacheItem.Value as T);
}
}
// Cached data item
static public List<string> GetMyDataList()
{
// define a function that retrieves data
// if data is not already present in cache
Func<List<String>> retriever = () =>
{
var data = new List<string>();
// TODO: retrieve and set data from storage
return data;
};
return Get<List<string>>("MY_DATA_LIST_KEY",
retriever, DEFAULT_CACHE_TIME_SECONDS);
}
// define methods for other cached data items
}
// accessing the cache data
var myDataList = CachedData.GetMyDataList();