protected void Load_Click(object sender, EventArgs e)
{
AddFileContentsToCache("TextFile.Txt");
}
void AddFileContentsToCache(string fileName)
{
string file = Server.MapPath(fileName);
StreamReader reader = new StreamReader(file);
string buf = reader.ReadToEnd();
reader.Close();
CreateAndCacheItem(buf, file);
if (Cache["MyData"] != null)
TextBox1.Text = Cache["MyData"].ToString();
}
void CreateAndCacheItem(object buf, string file)
{
CacheItemRemovedCallback removal;
removal = new CacheItemRemovedCallback(ReloadItemRemoved);
// 建立文件关联,如果文件被改动过,则存储在cache中的内容变为无效并且设置内容有效期为5秒
CacheDependency dep = new CacheDependency(file);
Cache.Insert("MyData", buf, dep, Cache.NoAbsoluteExpiration,TimeSpan.FromSeconds(5)
, CacheItemPriority.Normal, removal);
}
// 定义cache内容删除时的回调函数
void ReloadItemRemoved(string key, object value, CacheItemRemovedReason reason)
{
if (reason == CacheItemRemovedReason.DependencyChanged)
{
if (key == "MyData")
AddFileContentsToCache("TextFile.Txt");
}
}
protected void Remove_Click(object sender, EventArgs e)
{
Cache.Remove("MyData");
}
protected void Read_Click(object sender, EventArgs e)
{
object data = Cache["MyData"];
if (data == null)
{
TextBox1.Text = "No Content";
return;
}
TextBox1.Text = data.ToString();
}