后台数据缓存的一点心得

最近在实际使用中发现,当IIS应用程序池自动回收后,此时访问页面,会提示 “未将对象引用设置到对象的实例”的错误,查看代码发现,使用了类中的静态变量。

public static List<ReportData> = new List<ReportData>();

单看这个问题不大,因为此变量在类中,应用程序池回收后,因为类本身不是static,且不能变为static,所以要加以改造。

使用类单例模式,就可以比较好的解决这一问题。

因为类单例模式,在运行时实例唯一,这是做缓存的根本。

    public class EMPDataInterfaceDataCacheO : EMPDataCacheO
    {
        /// <summary>
        /// 数据接口中缓存类
        /// </summary>
        public class ListData : CacheListData { }
        /// <summary>
        /// 超时时间,3分钟
        /// </summary>
        private const int OverTime = 3;
        /// <summary>
        /// 缓存列表
        /// </summary>
        private List<ListData> cacheList;
        /// <summary>
        /// EMPDataInterfaceDataCache 实例
        /// </summary>
        private static EMPDataInterfaceDataCacheO cache;
        /// <summary>
        /// 获得缓存实例
        /// </summary>
        /// <returns>实例</returns>
        public static EMPDataInterfaceDataCacheO GetInstance()
        {
            if (cache == null)
            {
                cache = new EMPDataInterfaceDataCacheO();
            }
            return cache;
        }

        private EMPDataInterfaceDataCacheO()
        {
            cacheList = new List<ListData>();
        }
    }

以上是部分代码,类中实现了,缓存数据的存取,过期的自动清理等。

posted @ 2021-12-10 22:04  sonicit  阅读(135)  评论(0编辑  收藏  举报