摘要
在对winform做的项目优化的时候,首先想到的是对查询,并不经常变化的数据进行缓存,但对web项目来说有System.Web.Caching.Cache类进行缓存,那么winform端该如何呢?你可能会想到,存到文件中,但那可能有问题,文件操作权限问题,IO操作性能问题。
解决办法
针对exe的项目,可以使用MemoryCache这个类,进行内存级别的缓存。
辅助类
////// 基于MemoryCache的缓存辅助类 /// public static class MemoryCacheHelper { private static readonly Object _locker = new object(); public static T FindCacheItem(string key, Func 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]; } /// /// 移除缓存 /// /// 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(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 (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 (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; } }
参考