您的位置:首页 > 编程语言 > ASP

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

2011-09-30 00:26 260 查看
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 中,可以使用多个缓存实现来缓存数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: