private TEntity GetItem(TKey key) { // 为空的key,直接返回null,不进行缓存查找 if (key == null) { return(null); } if (Type.GetTypeCode(typeof(TKey)) == TypeCode.String) { String value = key as String; if (String.IsNullOrEmpty(value)) { return(null); } } // 更新统计信息 XCache.CheckShowStatics(ref NextShow, ref Total, ShowStatics); // 如果找到项,返回 CacheItem item = null; if (Entities.TryGetValue(key, out item) && item != null) { Interlocked.Increment(ref Shoot1); return(GetItem(item, key)); } // 加锁 lock (Entities) { // 如果找到项,返回 if (Entities.TryGetValue(key, out item) && item != null) { Interlocked.Increment(ref Shoot2); return(GetItem(item, key)); } item = new CacheItem(); item.Key = key; //队列满时,移除最老的一个 if (Entities.Count >= MaxEntity) { TKey keyFirst = GetFirstKey(); if (keyFirst != null && (Type.GetTypeCode(typeof(TKey)) != TypeCode.String || String.IsNullOrEmpty(keyFirst as String))) { CacheItem item2 = null; if (Entities.TryGetValue(keyFirst, out item2) && item2 != null) { if (Debug) { DAL.WriteLog("单实体缓存{0}超过最大数量限制{1},准备移除第一项{2}", typeof(TEntity).FullName, MaxEntity, keyFirst); } Entities.Remove(keyFirst); //自动保存 if (AutoSave && item2.Entity != null) { InvokeFill(delegate { item2.Entity.Update(); }); } } } } //查找数据 //TEntity entity = FindKeyMethod(key); TEntity entity = null; InvokeFill(delegate { entity = FindKeyMethod(key); }); if (entity != null || AllowNull) { item.Entity = entity; item.ExpireTime = DateTime.Now.AddSeconds(Expriod); if (!Entities.ContainsKey(key)) { Entities.Add(key, item); } } else { Interlocked.Increment(ref Invalid); } return(entity); } }