[Winform]缓存处理

摘要

在对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

posted @   wolfy  阅读(3828)  评论(1编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
历史上的今天:
2016-07-28 [Json.net]忽略不需要的字段
点击右上角即可分享
微信分享提示