内存管理

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsigneeMonitorService.Common;
using System.Timers;

namespace ConsigneeMonitorService.Model
{
    public class HadSendManage
    {
        private static List<MonitorCacheState> MonitorCacheStateList = new List<MonitorCacheState>();
        private static Timer timer = null;
        private static object locks = new object();

        static HadSendManage()
        {
            timer = new Timer();
            timer.Interval = 1000 * 60 * 60;
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }

        private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            List<MonitorCacheState> temp = new List<MonitorCacheState>();
            lock (locks)
            {
                foreach (var item in MonitorCacheStateList)
                {
                    if (DateTime.Compare(item.ExpireTime, DateTime.Now) <= 0) temp.Add(item);
                }
            }
            foreach (var item in temp)
            {
                lock (locks)
                {
                    if (MonitorCacheStateList.Any(m => m.Id == item.Id)) MonitorCacheStateList.Remove(item);
                }
            }
        }

        public static void Add(int id, string hadsend)
        {
            Add(id, hadsend, 0);
        }

        public static void Add(int id, string hadsend, double expireTime)
        {
            lock (locks)
            {
                var state = MonitorCacheStateList.FirstOrDefault(m => m.Id == id);
                if (state == null)
                {
                    MonitorCacheState _state = new MonitorCacheState();
                    _state.Id = id;
                    _state.ExpireInterval = expireTime;
                    _state.HadSend = new List<string>() { hadsend };
                    MonitorCacheStateList.Add(_state);
                }
                else
                {
                    state.ExpireInterval = expireTime;
                    if (!state.HadSend.Any(m => m == hadsend)) state.HadSend.Add(hadsend);
                }
            }
        }

        public static bool IsHadSend(int id,string hadSend)
        {
            var state = MonitorCacheStateList.FirstOrDefault(m => m.Id == id);
            if (state == null || !state.HadSend.Contains(hadSend)) return false;
            return true;
        }

    }

    public class MonitorCacheState
    {
        public int Id { get; set; }
        public double ExpireInterval { get; set; }//过期间隔,单位小时
        public DateTime ExpireTime { get { return DateTime.Now.AddHours(ExpireInterval); } }//时期时间
        public List<string> HadSend { get; set; }

    }
}

 

posted @ 2018-04-09 16:38  花生打代码会头痛  阅读(105)  评论(0)    收藏  举报