zoukankan      html  css  js  c++  java
  • 基于Dictionary实现的Cache类

    public static class Cache
        {
            private static readonly Timer CleanupTimer = new Timer() { AutoReset=true,Enabled=true,Interval=60000 };
            private static readonly Dictionary<string,CacheItem> InternalCache = new Dictionary<string,CacheItem>();
    
            static Cache()
            {
                CleanupTimer.Elapsed+=Clean;
                CleanupTimer.Start();
            }
    
            private static void Clean(object sender,ElapsedEventArgs e)
            {
                InternalCache.Keys.ToList().ForEach(x => { try { if(InternalCache[x].ExpireTime<=e.SignalTime) { Remove(x); } } catch(Exception) { /*swallow it*/ } });
            }
    
            public static bool ContainsKey(string key)
            {
                return InternalCache.ContainsKey(key);
            }
    
            public static T Get<T>(string key,int expiresMinutes,Func<T> refreshFunction)
            {
                if(InternalCache.ContainsKey(key)&&InternalCache[key].ExpireTime>DateTime.Now)
                {
                    return (T)InternalCache[key].Item;
                }
    
                var result = refreshFunction();
    
                Set(key,result,expiresMinutes);
    
                return result;
            }
    
            public static void Set(string key,object item,int expiresMinutes)
            {
                Remove(key);
    
                InternalCache.Add(key,new CacheItem(item,expiresMinutes));
            }
    
            public static void Remove(string key)
            {
                if(InternalCache.ContainsKey(key))
                {
                    InternalCache.Remove(key);
                }
            }
    
            private struct CacheItem
            {
                public CacheItem(object item,int expiresMinutes)
                    : this()
                {
                    Item=item;
                    ExpireTime=DateTime.Now.AddMinutes(expiresMinutes);
                }
    
                public object Item { get; private set; }
                public DateTime ExpireTime { get; private set; }
            }
        }
  • 相关阅读:
    OSError: Initializing from file failed
    python之邮件提醒
    python之经纬度的获取
    Pandas写入CSV格式
    代码不同之处高亮显示
    Python之免费随机代理IP的获取以及使用
    正则之利用元素属性进行匹配
    时间戳的格式化
    简单实用的HTML中字符串的提取
    承接OpenCV Halcon视觉项目开发定制
  • 原文地址:https://www.cnblogs.com/iot1024/p/5945814.html
Copyright © 2011-2022 走看看