ASP.NET 2.0缓存技术探讨
摘要:本文介绍通过缓存来提高网页的执行效率,包括ASP.NET Output Caching、Page Fragment Caching等内容。
[1] ASP.NET Output Caching[2] Page Fragment Caching
[3] Data Caching
[4] SQL Cache
3. Data Caching(数据缓存)
ASP.NET提供了一种非常快捷的方法进行数据库缓存,用户可以非常方便的对页面变量进行缓存。并以此提高程序效率。
一个页面变量的缓存生命周期与应用程序的缓存生命周期相同。
同时对后台数据进行修改的时候,还需要对Cache进行相应的处理。
示例:使用数据缓存示例:
<%@ Page Language="vb" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script runat="server">
Sub Page_Load(ByVal Src As Object, ByVal E As EventArgs)
Dim Source As DataView
' try to retrieve item from cache
' if it's not there, add it
Source = Cache("MyDataSet")
If Source Is Nothing Then
Dim MyConnection As SqlConnection
Dim MyCommand As SqlDataAdapter
MyConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("pub
sConnectionString").ConnectionString)
MyCommand = New SqlDataAdapter("select * from Authors", MyConnection)
Dim ds As New DataSet
MyCommand.Fill(ds, "Authors")
Source = New DataView(ds.Tables("Authors"))
Cache("MyDataSet") = Source
CacheMsg.Text = "Dataset created explicitly"
Else
CacheMsg.Text = "Dataset retrieved from cache"
End If
MyGrid.DataSource = Source
MyGrid.DataBind()
End Sub
</script>
<body>
<form id="Form1" runat="server">
<h3>
<font face="Verdana">Caching Data</font></h3>
<asp:GridView ID="MyGrid" runat="server">
</asp:GridView>
<p>
<i>
<asp:Label ID="CacheMsg" runat="server" /></i>
</p>
</form>
</body>
</html>