using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using DBHelper; using System.Data; using MySql.Data.MySqlClient; using System.Web.Caching; public partial class 缓存过期 : System.Web.UI.Page { static bool itemremove = false; static CacheItemRemovedReason reson; CacheItemRemovedCallback onremove = null; public void removeCallback(string k, object v, CacheItemRemovedReason r) { itemremove = true; reson = r; } protected void Page_Load(object sender, EventArgs e) { DataSet ds = (DataSet)Cache["students"]; if (ds == null) { ds = GetStudent(); onremove=new CacheItemRemovedCallback(this.removeCallback); CacheDependency cd=new CacheDependency(Server.MapPath("web.config")); Cache.Insert("students", ds, cd, Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1), CacheItemPriority.High, onremove); } GridView1.DataSource = ds; GridView1.DataBind(); } protected void Button1_Click(object sender, EventArgs e) { if (Cache["students"] != null) { Cache.Remove("students"); } if (itemremove) { Label1.Text += "REmove触发"; Label1.Text += "<br>"; Label1.Text += reson.ToString(); } else { Label1.Text += Server.HtmlEncode(Cache["students"] as string); } } public static void SetCache(string CacheKey, object objObject, System.Web.Caching.CacheDependency dep) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert( CacheKey, objObject, dep, System.Web.Caching.Cache.NoAbsoluteExpiration, //从不过期 System.Web.Caching.Cache.NoSlidingExpiration, //禁用可调过期 System.Web.Caching.CacheItemPriority.Default, null); } public static object GetCache(string CacheKey) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; return objCache[CacheKey]; } public DataSet GetStudent() { string sql = "select * from t_student"; return SqlHelper.ExecuteDataSetText(sql); } }