/// <summary> /// 添加到缓存 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="aliveSeconds">存活时间(秒)</param> public static void Set(string key, object value, int aliveSeconds) { if (!Enable) { return; } if (aliveSeconds == 0) { return; } if (aliveSeconds < 0) { throw new Exception("aliveSeconds should great than zero"); } CacheLabel cacheLabel; if (dictonary.TryGetValue(key, out cacheLabel)) { cacheLabel.Value = value; } else { cacheLabel = new CacheLabel(value); lock (dicChangeLock) { if (!dictonary.ContainsKey(key)) { dictonary.Add(key, cacheLabel); } } } cacheLabel.AliveSeconds = aliveSeconds; }
static Cache() { timerForSetFade = new Timer(p => { lock (dicChangeLock) { DateTime now = DateTime.Now; foreach (var value in dictonary.Values) { var time = now - value.LastGetTime; if (time.TotalSeconds > value.AliveSeconds) { value.Faded = true; } } } }, null, 0, 1000 * 5); timerForRemoveCacheElement = new Timer(p => { lock (dicChangeLock) { var toRemove = new List <string>(); var enumerator = dictonary.GetEnumerator(); while (enumerator.MoveNext()) { if (enumerator.Current.Value.Faded) { toRemove.Add(enumerator.Current.Key); } } CacheLabel label = enumerator.Current.Value; toRemove.ForEach(key => dictonary.Remove(key)); } }, null, 0, 1000 * 60); }