Session 的生命周期

#region EntityMap

        /// <summary>
        /// 实体类值的访问器,线程安全
        /// </summary>
        /// <typeparam name="TKey"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        public class EntityMap<TKey, TValue>
        {
            private readonly ConcurrentDictionary<TKey, TValue> map = new ConcurrentDictionary<TKey, TValue>();

            /// <summary>
            /// 获得一个值
            /// </summary>
            /// <typeparam name="TKey"></typeparam>
            /// <param name="key"></param>
            /// <returns>如果key找不到对应值,返回null</returns>
            public TValue GetValue(TKey key)
            {
                TValue value;
                if (map.TryGetValue(key, out value))
                    return value;

                return default(TValue);
            }

            /// <summary>
            /// 设置一个值
            /// </summary>
            /// <param name="key"></param>
            /// <param name="value"></param>
            public void SetValue(TKey key, TValue value)
            {
                if (arrayCache != null)
                {
                    TValue mapValue;
                    if (map.TryGetValue(key, out mapValue))
                    {
                        if (!mapValue.Equals(value))
                            arrayCache = null;
                    }
                    else
                    {
                        arrayCache = null;
                    }
                }
                map[key] = value;
            }

            /// <summary>
            /// 缓存map的数据
            /// </summary>
            private TValue[] arrayCache;

            /// <summary>
            /// 获得所有的数据(内部有缓存,如果数据没改变过,则返回同一个数组)
            /// </summary>
            /// <returns></returns>
            public TValue[] ToArray()
            {
                if (arrayCache == null)
                    arrayCache = map.Values.ToArray();

                return arrayCache;
            }

            /// <summary>
            /// 删除一个数据
            /// </summary>
            /// <param name="key"></param>
            public void Remove(TKey key)
            {
                TValue value;
                if (map.TryRemove(key, out value))
                    arrayCache = null;
            }

            public void Clear()
            {
                map.Clear();
                arrayCache = null;
            }
        }

        #endregion

至于Session 的生命周期很好处理 自己封装一个时间片类 规定Session创建后什么时候移除
待会我再上传时间片代码

posted @ 2016-08-22 11:59  芜明-追星  阅读(221)  评论(0编辑  收藏  举报