MemoryCache緩存 ---緩存時效
阿新 • • 發佈:2018-05-25
HA mem pre stc val key 變化 guid tor
MemoryCache緩存 ---緩存時效測試
var cachePool = new MyCachePool();
//Thread.Sleep(1000);
var value = cachePool.GetFileValue();
/// <summary> /// MemoryCache緩存 /// </summary> public class MyCachePool { ObjectCache cache = MemoryCache.Default; const string cacheKey = "View CodeTestCacheKey"; public string GetValue() { var content = cache[cacheKey] as string; if (content == null) { //Console.WriteLine("Get New Item"); var policy = new CacheItemPolicy() { AbsoluteExpiration = DateTime.Now.AddSeconds(5) }; content = Guid.NewGuid().ToString(); cache.Set(cacheKey, content, policy); } else { Console.WriteLine("Get cached item"); } return content; } public string GetFileValue() {string strCacheKey = "FileCacheKey"; var content = cache[strCacheKey] as string; if (content == null) { //Console.WriteLine("Get New Item"); //var file = @"E:\test.txt"; //CacheItemPolicy policy = new CacheItemPolicy(); //policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string> { file })); //content = File.ReadAllText(file); //cache.Set(strCacheKey, content, policy); CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(3); content = Guid.NewGuid().ToString(); CacheItem item = new CacheItem("cachedText", content); List<string> keys = new List<string> { strCacheKeyChange }; policy.ChangeMonitors.Add(cache.CreateCacheEntryChangeMonitor(keys)); //依賴某個值變化 cache.Set(item, policy); } else { Console.WriteLine("Get cached item"); } return content; } }
MemoryCache緩存 ---緩存時效