通用缓存信息类

来源:互联网 发布:linux虚拟机 限制cpu 编辑:程序博客网 时间:2024/04/30 04:54
using System;using System.Collections.Generic;using System.Collections;using System.Text;using System.Web;using System.Web.Caching;using System.Data;namespace test{    /// <summary>    /// M缓存类       /// </summary>    public class CommonCache    {        #region 构造函数        /// <summary>        /// 静态构造函数        /// </summary>        static CommonCache()        {        }        #endregion        #region 属性定义        /// <summary>        /// 失效时间单位为分钟        /// </summary>        public static int LoseTime        {            set            {                mLoseTime = value;            }        }               #endregion        #region 公共方法        /// <summary>        /// 获取值        /// </summary>        /// <param name="pKey">键值名</param>        /// <returns>返回键值</returns>        public static object GetValue(object pKey)        {            object  retValue = null;            lock (mCache.SyncRoot)            {                try                {                    if (mCache.ContainsKey(pKey))                    {                        retValue=mCache[pKey];                        IList<object> valueArr = (IList<object>)retValue;                        DateTime dt = Convert.ToDateTime(valueArr[0]);                        if (dt.CompareTo(DateTime.Now) < 0)                        {                            retValue = null;                        }                        else                        {                            retValue = valueArr[1];                        }                    }                    else                    {                        retValue = null;                    }                }                catch (Exception e)                {                    retValue = null;                }            }            return retValue;        }        /// <summary>        /// 设置值        /// </summary>        /// <param name="pKey">键值名</param>        /// <param name="pValue">键值</param>        public static void SetValue(object pKey, object pValue)        {            IList<object> valueArr = new List<object>() ;            valueArr.Add (DateTime.Now.AddMinutes(mLoseTime));            valueArr.Add ( pValue);            lock (mCache.SyncRoot)            {                try                {                    if (!mCache.ContainsKey(pKey))                    {                        mCache.Add(pKey, valueArr);                    }                    else                    {                        mCache[pKey] = valueArr;                    }                }                catch (Exception e)                {                }            }        }        #endregion        #region 字段定义        /// <summary>        /// 缓存对象        /// </summary>        private static Hashtable mCache = new Hashtable();        /// <summary>        /// 失效时间(单位:分钟)        /// </summary>        private static int mLoseTime = 60;        #endregion    }}