在 ASP.NET 中缓存应用程序数据

 1、添加引用: System.Runtime.Caching

2、添加命名空间

using System.Runtime.Caching;
using System.IO;
3、

 

 

完成本演练后,您创建的网站的代码将与下面的示例类似。

C#
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Caching;
using System.IO;

 public partial class _Default : System.Web.UI.Page

    {

        protected void Button1_Click1(object sender, EventArgs e)

        {             ObjectCache cache = MemoryCache.Default;  // ObjectCache 是一个基类,提供用于实现在内存中缓存对象的方法。

            string fileContents = cache["filecontents"] as string;//读取名为 filecontents 的缓存项的内容

            //检查是否存在名为 filecontents 的缓存项。                   //如果指定的缓存项不存在,则您必须读取该文本文件并将其作为一个缓存项添加到缓存。

            if (fileContents == null)

            {

                CacheItemPolicy policy = new CacheItemPolicy();

                policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.0); 

 

//创建一个新的 CacheItemPolicy 对象,该对象指定缓存将在 10 秒后过期。

                //为要监视的文件路径创建一个集合,并向该集合中添加文本文件的路径。

                List<string> filePaths = new List<string>();

                string cachedFilePath = Server.MapPath("~") +"\\cacheText.txt";

 

                filePaths.Add(cachedFilePath);

                //将新的 HostFileChangeMonitor 对象添加到缓存项的更改监视集合。                 //HostFileChangeMonitor 对象将监视文本文件的路径并向缓存通知是否发生更改。 在此示例中,如果文件的内容发生更改,则缓存项将自动过期。                 policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePaths));

 

                // Fetch the file contents.  读取文本文件的内容。并添加事件标志来鉴别缓存与否

                fileContents = File.ReadAllText(cachedFilePath) + "\n" + DateTime.Now.ToString();

 

                //将文件内容作为 CacheItem 实例插入到缓存对象。                 //通过将 CacheItemPolicy 对象作为参数传递给 Set 方法,指定有关应如何逐出缓存项的信息。

                cache.Set("filecontents", fileContents, policy);

 

            }

 

            //在 Label 控件中显示缓存的文件内容。

            Label1.Text = fileContents;

        }

    }


在 ASP.NET 中,可以使用多个缓存实现来缓存数据。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值