public TimerPool_Item Add(int timerInterval, TimerPoolItemCallback callback, object state = null, bool isStart = true) { var item = new TimerPool_Item(this, callback, state, timerInterval); lock (lockerObj) { var index = -1; //查找第一个小于10000个托管定时任务的定时列表 if (_delgateList.Count > 0) { for (int i = 0; i < _delgateList.Count; i++) { if (_delgateList[i].Count < 10000) { index = i; break; } } } //如果都大于或等于10000的话,则添加一个新的 if (index == -1) { var newList = new List <TimerPool_Item>(1000); _delgateList.Add(newList); index = _delgateList.Count - 1; var newtimer = new TimerEx(CheckerList, 2000, newList); _checkTimer.Add(newtimer); if (isStart) { newtimer.Start(); } } _delgateList[index].Add(item); if (_delgateList.Count > 3) { _delgateList.Sort((x, y) => x.Count.CompareTo(y.Count)); } } return(item); }
public void Remove(TimerPool_Item timerPoolItem) { lock (lockerObj) { List <int> tempLst = null; var _delgateListCount = _delgateList.Count; for (int i = 0; i < _delgateListCount; i++) { var lst = _delgateList[i]; lock (lst) { lst.Remove(timerPoolItem); if (lst.Count <= 0 && _delgateListCount > 1) { if (tempLst == null) { tempLst = new List <int>(_delgateList.Count / 2); } tempLst.Add(i); } } } if (tempLst != null && tempLst.Count > 0) { foreach (var index in tempLst) { _delgateList.RemoveAt(index); var timer = _checkTimer[index]; timer.Dispose(); _checkTimer.RemoveAt(index); } } } }
/// <summary> /// 创建自动过期 /// </summary> /// <param name="creator">创建函数</param> /// <param name="expireSec">过期秒数,单位是秒</param> public AutoExpireValue(Func <T> creator, int expireSec) { _creator = creator; _expireSec = expireSec; _timerItem = TimerPool.Default.Add(_expireSec * 1000, timer_Callback, null, true); }