/// <summary> /// 固态的缓存容器,提供了相关的基本操作 /// </summary> /// <param name="capacity">最大容量</param> /// <exception cref="ArgumentException">错误的参数取值范围</exception> public FixedCacheContainer(int capacity) { if (capacity <= 0) { throw new ArgumentException("Illegal capacity!"); } _remainingCount = _capacity = capacity; _caches = new Stack <ICacheStub <T> >(); //initialize. for (int i = 0; i < _capacity; i++) { ICacheStub <T> stub = new CacheStub <T> { Fixed = true }; ((CacheStub <T>)stub).Id = i; stub.Cache = new CacheItem <T>(); stub.Cache.SetValue(new T()); _caches.Push(stub); } }
/// <summary> /// 添加一个新的缓存 /// </summary> /// <param name="key">缓存Key</param> /// <param name="obj">要缓存对的象</param> /// <param name="expireTime">过期时间</param> /// <returns>返回缓存对象</returns> /// <exception cref="LeaseDeadException">当前缓存已经处于死亡状态</exception> public IReadonlyCacheStub <V> Add(K key, V obj, DateTime expireTime) { if (IsDead) { throw new LeaseDeadException("Cannot execute add operation on a dead container."); } ICacheStub <V> stub = new CacheStub <V>(expireTime) { Cache = new CacheItem <V>() }; stub.Cache.SetValue(obj); lock (_lockObj) { ICacheStub <V> tmpStub; if (!_caches.TryGetValue(key, out tmpStub)) { _caches.Add(key, stub); } return((IReadonlyCacheStub <V>)stub); } }