ASP.NET 中有专门实现缓存的类,而且不止一个。但本文介绍一个用静态字段巧妙实现缓存的方法,static 的内容是全局,所有会话都共享该数据。
public partial class _Default : System.Web.UI.Page
{
private static string _cache = ""; // 用静态“缓存”的内容
private static DateTime _cacheUpdateTime = DateTime.Now.AddYears(-100); // “缓存”最后更新时间,初始为 100 年前,这看作是过期的
protected void Page_Load(object sender, EventArgs e)
{
if ((DateTime.Now - _cacheUpdateTime).TotalSeconds <= 10)
{
// 上次更新时间是 10 秒以内,“缓存”内容有效。
Response.Write("<p>" + _cache + "</p>");
}
else
{
// “缓存”内容已经失效,重新生成。
GenerateData();
Response.Write("<p>" + _cache + "</p>");
Response.Write("<p>调用了 GenerateData 产生缓存内容。</p>");
}
}
private void GenerateData()
{
_cache = "缓存的内容 " + DateTime.Now.ToString() + "。";
_cacheUpdateTime = DateTime.Now;
}
}