摘要
在對winform做的項目優化的時候,首先想到的是對查詢,並不經常變化的數據進行緩存,但對web項目來說有System.Web.Caching.Cache類進行緩存,那么winform端該如何呢?你可能會想到,存到文件中,但那可能有問題,文件操作權限問題,IO操作性能問題。
解決辦法
針對exe的項目,可以使用MemoryCache這個類,進行內存級別的緩存。
輔助類
/// <summary> /// 基於MemoryCache的緩存輔助類 /// </summary> public static class MemoryCacheHelper { private static readonly Object _locker = new object(); public static T FindCacheItem<T>(string key, Func<T> cachePopulate, TimeSpan? slidingExpiration = null,
DateTime? absoluteExpiration = null) { if (String.IsNullOrWhiteSpace(key)) { throw new ArgumentException("Invalid cache key"); } if (cachePopulate == null) { throw new ArgumentNullException("cachePopulate"); } if (slidingExpiration == null && absoluteExpiration == null) { throw new ArgumentException("Either a sliding expiration or absolute must be provided"); } if (MemoryCache.Default[key] == null) { lock (_locker) { if (MemoryCache.Default[key] == null) { var item = new CacheItem(key, cachePopulate()); var policy = CreatePolicy(slidingExpiration, absoluteExpiration); MemoryCache.Default.Add(item, policy); } } } return (T)MemoryCache.Default[key]; } /// <summary> /// 移除緩存 /// </summary> /// <param name="key"></param> public static void RemoveCache(string key) { MemoryCache.Default.Remove(key); } private static CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration) { var policy = new CacheItemPolicy(); if (absoluteExpiration.HasValue) { policy.AbsoluteExpiration = absoluteExpiration.Value; } else if (slidingExpiration.HasValue) { policy.SlidingExpiration = slidingExpiration.Value; } policy.Priority = CacheItemPriority.Default; return policy; } }
測試
class Program { static void Main(string[] args) { string cacheKey = "person_key"; Person p = MemoryCacheHelper.FindCacheItem<Person>(cacheKey, () => { return new Person() { Id = Guid.NewGuid(), Name = "wolfy" }; }, new TimeSpan(0, 30, 0)); if (p != null) { Console.WriteLine(p.ToString()); } Console.WriteLine("獲取緩存中數據"); Person p2 = MemoryCacheHelper.FindCacheItem<Person>(cacheKey, () => { return new Person() { Id = Guid.NewGuid(), Name = "wolfy" }; }, new TimeSpan(0, 30, 0)); if (p2 != null) { Console.WriteLine(p2.ToString()); } MemoryCacheHelper.RemoveCache(cacheKey); Person p3 = MemoryCacheHelper.FindCacheItem<Person>(cacheKey, () => { return new Person() { Id = Guid.NewGuid(), Name = "wolfy" }; }, new TimeSpan(0, 30, 0)); if (p3 != null) { Console.WriteLine(p3.ToString()); } Console.Read(); } } public class Person { public Guid Id { set; get; } public string Name { set; get; } public override string ToString() { return Id.ToString() + "\t" + Name; } }
參考
http://www.cnblogs.com/ldy_ai/p/3939954.html
https://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache(v=vs.110).aspx