Asp.net中使用缓存(cache)

做了一个时间优化的项目,目的就是缩短程序过程中的时间花费,最后发现了asp.net和asp.net core 中都有缓存工具来进行缓存,以加快访问速度。

找了官方demo来进行分析:

      ObjectCache cache = MemoryCache.Default;
            string fileContents = cache["filecontents"] as string; //获取缓存值
            if (fileContents == null)
            {
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.0);//设置缓存失效时间
                List<string> filePaths = new List<string>();
                string cachedFilePath = Server.MapPath("~") + "\\cacheText.txt";

                filePaths.Add(cachedFilePath);
                policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));
                fileContents = System.IO.File.ReadAllText(cachedFilePath, Encoding.Default);

                cache.Set("filecontents", fileContents, policy);//设置缓存中
            }
            return fileContents;

官方参考路径:https://docs.microsoft.com/en-us/dotnet/framework/performance/caching-in-net-framework-applications

posted @ 2019-01-16 18:13  翱翔的小鱼  阅读(350)  评论(0编辑  收藏  举报