ASP.Net使用缓存技术提高效率

2008-02-22 09:33:24来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

ASP.Net的缓存技术大大地提高了效率,本人将代码的简单的实现代码贴出:

一、在页面中显示时,读缓存数据,加载XML数据

public void LoadData()
{
DataView Source = (DataView)Cache["MyData"];
if(Source == null)
{
DataSet ds = new DataSet();
FileStream fs = new FileStream(Server.MapPath("LoginMsg.xml"), FileMode.Open,FileAccess.Read);
StreamReader reader = new StreamReader(fs);
ds.ReadXml(reader);
fs.Close();
Source = new DataView(ds.Tables[0]);
Cache.Insert("MyData", Source, new CacheDependency(Server.MapPath("LoginMsg.xml")));
ErrorMsg.Text = "从文件中读取的数据";
}
else
{
ErrorMsg.Text = "从缓存中读取的数据";
}
MyDataGrid.DataSource = Source;
MyDataGrid.DataBind();
}

二、用XML存储交互数据,将数据放置到缓存中

private void LoginMsg_Click(object sender, System.EventArgs e)
{
if(!Page.IsValid)
{
ErrorMsg.Text = "必需输入登录信息";
return;
}
DataSet ds = new DataSet();
FileStream fs = new FileStream(Server.MapPath("LoginMsg.xml"),FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader reader = new StreamReader(fs);
ds.ReadXml(reader);
fs.Close();
DataTable dt = ds.Tables[0];
DataRow newrow = dt.NewRow();
newrow["custom_email"] = CustomEamil.Text;
newrow["custom_pass"] = CustomPass.Text;
newrow["login_time"] = DateTime.Now.ToString();
fs = new FileStream(Server.MapPath("LoginMsg.xml"), FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
TextWriter writer = new StreamWriter(fs);
writer = TextWriter.Synchronized(writer);
ds.Tables[0].Rows.Add(newrow);
ds.WriteXml(writer);
writer.Close();
Cache.Remove("MyData");
LoadData();

}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Repeater读取数据并分页

下一篇:利用WebClient获取远程数据(仅做备份)