[C#]Cache Set And Get
實作:
*CacheHelper
/// <summary> /// 快取-Helper /// </summary> public static class CacheHelper { private static ObjectCache _cache = MemoryCache.Default; /// <summary> /// 設定 快取 /// </summary> /// <param name="key">快取Key</param> /// <param name="data">物件</param> /// <param name="cacheTime">快取保存時間(TimeSpan)</param> public static void Set(string key, object data, TimeSpan cacheTime) { CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTime.Now + cacheTime; _cache.Set(key, data, policy); } /// <summary> /// 取得 快取 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">快取Key</param> /// <param name="result">物件</param> /// <returns></returns> public static bool Get<T>(string key, ref T result) { try { var data = _cache[key]; if (data == null) { throw new Exception("No Value"); } result = (T)(Convert.ChangeType(data, typeof(T))); return true; } catch { return false; } } }
使用範例:
*Set
CacheHelper.Set(Key_MDESManufacturerInfo, list, TimeSpan.FromDays(14));
留言
張貼留言