asp.Net 缓存技术
asp.net 2.0 支持的缓存包括
1 页面输出缓存
页面输出缓存是将页面全部内容都保存在内存中,并用于完成客户端请求
  
点击超连接,读入参数location=beijing ,页面每隔5秒刷新一次
HTML部分
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm3.aspx.cs" Inherits="WebForm3" %>
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm3.aspx.cs" Inherits="WebForm3" %>
 <%@ OutputCache Duration ="5" VaryByParam="location"  %>
<%@ OutputCache Duration ="5" VaryByParam="location"  %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" >
 <head id="Head1" runat="server">
<head id="Head1" runat="server">
 <title>页面缓存应用1</title>
    <title>页面缓存应用1</title>
 <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />
    <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />    
 </head>
</head>
 <body>
<body>
 <form id="form1" runat="server">
    <form id="form1" runat="server">
 <div>
        <div>
 <fieldset style="width: 240px">
            <fieldset style="width: 240px">
 <legend class="mainTitle">设置页面输出缓存</legend>
                <legend class="mainTitle">设置页面输出缓存</legend>
 <br />
                <br />
 <center>
                <center>
 <asp:Label ID="Label1" runat="server" CssClass="commonText"></asp:Label></center>
                    <asp:Label ID="Label1" runat="server" CssClass="commonText"></asp:Label></center>
 <br />
                <br />
 <a href="WebForm3.aspx?location=beijing" class="littleMainTitle">缓存时间</a><br />
                    <a href="WebForm3.aspx?location=beijing" class="littleMainTitle">缓存时间</a><br />
 </fieldset>
            </fieldset>
 </div>
        </div>
 </form>
    </form>
 </body>
</body>
 </html>
代码部分
</html>
代码部分
 protected void Page_Load(object sender, EventArgs e)
  protected void Page_Load(object sender, EventArgs e)
 {
    {
 /*
        /*
 * 页面缓存
         * 页面缓存
 * 应用程序初始显示 的是停止执行缓存的时间,当用户刷新页面时,时间将随时变化
         * 应用程序初始显示 的是停止执行缓存的时间,当用户刷新页面时,时间将随时变化
 * 单击"缓存时间超连接以后,页面重新定位,这时页面显示时间被缓存,数据过期时间为5秒,如果不断刷新该页面,那么每隔5秒刷新一次
         * 单击"缓存时间超连接以后,页面重新定位,这时页面显示时间被缓存,数据过期时间为5秒,如果不断刷新该页面,那么每隔5秒刷新一次
 */
         */
 
      
 //设置仅将缓存数据存储在服务器上
            //设置仅将缓存数据存储在服务器上
 Response.Cache.SetCacheability(HttpCacheability.Server);
            Response.Cache.SetCacheability(HttpCacheability.Server);
 string temp_location = Request.QueryString["location"];
            string temp_location = Request.QueryString["location"];
 //如果location为空,则不缓存,否则根据@ OutputCache指令声明执行缓存
            //如果location为空,则不缓存,否则根据@ OutputCache指令声明执行缓存
 if (temp_location == null)
            if (temp_location == null)
 {
            {
 //停止当前响应的所有服务器缓存
                //停止当前响应的所有服务器缓存
 Response.Cache.SetNoServerCaching();
                Response.Cache.SetNoServerCaching();
 Label1.Text = "停止缓存的时间:" + DateTime.Now.ToString();
                Label1.Text = "停止缓存的时间:" + DateTime.Now.ToString();
 }
            }
 else
            else
 {
            {
 Label1.Text = "设置了缓存的时间:" + DateTime.Now.ToString();
                Label1.Text = "设置了缓存的时间:" + DateTime.Now.ToString();
 }
            }
 
      
 
        
 }
    }
 2 页面部分缓存
    
2 页面部分缓存
实现方式: 控件缓存和缓存后替换
控件缓存:允许将需要缓存的信息包含在一个用户控件内,然后将该控件标记为可缓存的,以此来缓存页面输出的部分内容
缓存后替换,使用缓存后替换机制,可以将页配置为进行缓存,将页的个别部分标记为不可缓存.
  
将整个页面输出缓存,然后实现缓存后替代
  
HTML部分
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm4.aspx.cs" Inherits="WebForm4" %>
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm4.aspx.cs" Inherits="WebForm4" %>

 <%@ OutputCache Duration="10" VaryByParam="None" %>
<%@ OutputCache Duration="10" VaryByParam="None" %>


 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" >
 <head runat="server">
<head runat="server">
 <title>无标题页</title>
    <title>无标题页</title>
 </head>
</head>
 <body>
<body>
 <form id="form1" runat="server">
   <form id="form1" runat="server">
 <div>
        <div>
 <fieldset style="width: 320px">
            <fieldset style="width: 320px">
 <legend class="mainTitle">使用Substitution控件实现页面部分缓存</legend>
              <legend class="mainTitle">使用Substitution控件实现页面部分缓存</legend>
 <br />
              <br />
 <div class="littleMainTitle">
                <div class="littleMainTitle">
 以下时间显示使用Substitution控件实现缓存后替换:</div>
                    以下时间显示使用Substitution控件实现缓存后替换:</div>
 <asp:Substitution ID="Substitution2" MethodName="GetCurrentDateTime" runat="Server">
                <asp:Substitution ID="Substitution2" MethodName="GetCurrentDateTime" runat="Server">
 </asp:Substitution>
                      </asp:Substitution>
 
               
 <hr />
                 <hr />
 <div class="littleMainTitle">
                  <div class="littleMainTitle">
 以下时间显示使用页面输出缓存,缓存时间为5秒:</div>
                    以下时间显示使用页面输出缓存,缓存时间为5秒:</div>
 <asp:Label ID="CachedDateLabel" runat="Server"></asp:Label>
                    <asp:Label ID="CachedDateLabel" runat="Server"></asp:Label>
 <br />
                     <br />
 <center>
                <center>
 <asp:Button ID="RefreshButton" Text="刷新页面" runat="Server"></asp:Button></center>
                <asp:Button ID="RefreshButton" Text="刷新页面" runat="Server"></asp:Button></center>
 
                
 <hr />
                <hr />
 <br>
                <br>
 <div class="littleMainTitle">
                <div class="littleMainTitle">
 以下时间显示使用Substitution控件API实现缓存后替换:</div>
                    以下时间显示使用Substitution控件API实现缓存后替换:</div>
 <%Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetCurrentDateTime)); %>
                <%Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetCurrentDateTime)); %>
 
                
 
                
 </fieldset>
            </fieldset>
 </div>
        </div>
 </form>
    </form>
 </body>
</body>
 </html>
</html>
代码部分
 protected void Page_Load(object sender, EventArgs e)
 protected void Page_Load(object sender, EventArgs e)
 {
    {
 CachedDateLabel.Text = DateTime.Now.ToString();
        CachedDateLabel.Text = DateTime.Now.ToString();
 }
    }
 public static string GetCurrentDateTime(HttpContext context)
    public static string GetCurrentDateTime(HttpContext context)
 {
    {
 return DateTime.Now.ToString();
        return DateTime.Now.ToString();
 }
    }
这里把整个页面设置为页面缓存,然后
<asp:Substitution ID="Substitution2" MethodName="GetCurrentDateTime" runat="Server">
</asp:Substitution>
和
<%Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetCurrentDateTime)); %>
实现了缓存替换
                      
3 应用程序数据缓存
提供了一种编程方式,可以通过键/值方式对将任意数据存储在内存中.
应用程序缓存的主要功能是在内存中存储各种与应用程序相关的对象
优点 :由asp.net管理缓存,他会在项过期,无效,或内存不足的时候移除缓存中的项,还可以配置应用程序缓存,以便在移除项的时候通知
应用程序实现对缓存的增加,删除,检索
对字符串数组tempArray进行操作,保存到数据缓存里面
html代码
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm5.aspx.cs" Inherits="WebForm5" %>
  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm5.aspx.cs" Inherits="WebForm5" %>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" >
 <head runat="server">
<head runat="server">
 <title>应用程序数据缓存</title>
     <title>应用程序数据缓存</title>
 <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />
    <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />
 </head>
</head>
 <body>
<body>
 <form id="form1" runat="server">
    <form id="form1" runat="server">
 <div>
        <div>
 <fieldset style="width: 310px">
            <fieldset style="width: 310px">
 <legend class="mainTitle">实现应用程序数据缓存</legend>
                <legend class="mainTitle">实现应用程序数据缓存</legend>
 <br />
                <br />
 <div class="commonText">
                <div class="commonText">
 字符串数组内容如下:</div>
                    字符串数组内容如下:</div>
 <div class="commonText" align="center">
                <div class="commonText" align="center">
 北京,上海,广州,成都,深圳</div>
                    北京,上海,广州,成都,深圳</div>
 <hr />
                <hr />
 <div>
                <div>
 <center>
                    <center>
 <asp:Button ID="btAdd" Text="添加" runat="Server" OnClick="AddItemToCache"></asp:Button>
                        <asp:Button ID="btAdd" Text="添加" runat="Server" OnClick="AddItemToCache"></asp:Button>
 <asp:Button ID="btGet" Text="检索" runat="Server" OnClick="GetItemFromCache"></asp:Button>
                        <asp:Button ID="btGet" Text="检索" runat="Server" OnClick="GetItemFromCache"></asp:Button>
 <asp:Button ID="btDel" Text="移除" runat="Server" OnClick="RemoveItemFromCache"></asp:Button>
                        <asp:Button ID="btDel" Text="移除" runat="Server" OnClick="RemoveItemFromCache"></asp:Button>
 <div>
                        <div>
 <asp:Label ID="lbCacheInfo" runat="server" CssClass="commonText" ForeColor="red"></asp:Label></div>
                            <asp:Label ID="lbCacheInfo" runat="server" CssClass="commonText" ForeColor="red"></asp:Label></div>
 </center>
                    </center>
 </div>
                </div>
 <hr />
                <hr />
 <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label>
                <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label>
 </fieldset>
            </fieldset>
 </div>
        </div>
 </form>
    </form>
 </body>
</body>
 </html>
</html>
代码部分
 using System;
using System;
 using System.Data;
using System.Data;
 using System.Configuration;
using System.Configuration;
 using System.Collections;
using System.Collections;
 using System.Web;
using System.Web;
 using System.Web.Security;
using System.Web.Security;
 using System.Web.UI;
using System.Web.UI;
 using System.Web.UI.WebControls;
using System.Web.UI.WebControls;
 using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls.WebParts;
 using System.Web.UI.HtmlControls;
using System.Web.UI.HtmlControls;
 using System.Web.Caching;
using System.Web.Caching;

 public partial class WebForm5 : System.Web.UI.Page
public partial class WebForm5 : System.Web.UI.Page
 {
{

 //声明变量
    //声明变量    
 static CacheItemRemovedReason reason;
    static CacheItemRemovedReason reason;
 string[] tempArray = { "北京", "上海", "广州", "成都", "深圳" };
    string[] tempArray = { "北京", "上海", "广州", "成都", "深圳" };
 //实现添加按钮的事件处理程序
    //实现添加按钮的事件处理程序
 protected void AddItemToCache(object sender, EventArgs e)
    protected void AddItemToCache(object sender, EventArgs e)
 {
    {
 //如果不存在,则添加;否则,只显示有关信息
        //如果不存在,则添加;否则,只显示有关信息
 if (Cache["tempArray"] == null)
        if (Cache["tempArray"] == null)
 {
        {
 Cache.Add("tempArray", tempArray, null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(ItemRemoved));
            Cache.Add("tempArray", tempArray, null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(ItemRemoved));
 lbMessage.Text += ">>>已经将字符串数组添加到缓存中 <br/>";
            lbMessage.Text += ">>>已经将字符串数组添加到缓存中 <br/>";
 }
        }
 else
        else
 {
        {
 lbMessage.Text += ">>>缓存中已经存在字符串数组 <br/>";
            lbMessage.Text += ">>>缓存中已经存在字符串数组 <br/>";
 }
        }
 //显示缓存信息
        //显示缓存信息
 DisplayCacheInfo();
        DisplayCacheInfo();
 }
    }
 //实现检索按钮的事件处理程序
    //实现检索按钮的事件处理程序
 protected void GetItemFromCache(object sender, EventArgs e)
    protected void GetItemFromCache(object sender, EventArgs e)
 {
    {
 //根据是否存在,显示信息
        //根据是否存在,显示信息
 if (Cache["tempArray"] != null)
        if (Cache["tempArray"] != null)
 {
        {
 lbMessage.Text += ">>>已检索到缓存中包括字符串数组 <br/>";
            lbMessage.Text += ">>>已检索到缓存中包括字符串数组 <br/>";
 }
        }
 else
        else
 {
        {
 lbMessage.Text += ">>>未检索到缓存中包括字符串数组 <br/>";
            lbMessage.Text += ">>>未检索到缓存中包括字符串数组 <br/>";
 }
        }
 //显示缓存信息
        //显示缓存信息
 DisplayCacheInfo();
        DisplayCacheInfo();
 }
    }
 //实现删除按钮的事件处理程序
    //实现删除按钮的事件处理程序
 protected void RemoveItemFromCache(object sender, EventArgs e)
    protected void RemoveItemFromCache(object sender, EventArgs e)
 {
    {
 //如果不存在,则显示信息;否则,调用方法移除
        //如果不存在,则显示信息;否则,调用方法移除
 if (Cache["tempArray"] == null)
        if (Cache["tempArray"] == null)
 {
        {
 lbMessage.Text += ">>>未缓存字符串数组,无法删除<br/>";
            lbMessage.Text += ">>>未缓存字符串数组,无法删除<br/>";
 }
        }
 else
        else
 {
        {
 Cache.Remove("tempArray");
            Cache.Remove("tempArray");
 lbMessage.Text += ">>>已经调用 CacheItemRemovedCallback 委托方法,缓存移除原因是:" + reason.ToString() + "<br/>";
            lbMessage.Text += ">>>已经调用 CacheItemRemovedCallback 委托方法,缓存移除原因是:" + reason.ToString() + "<br/>";
 lbMessage.Text += ">>>已删除字符串数组缓存<br/>";
            lbMessage.Text += ">>>已删除字符串数组缓存<br/>";
 }
        }
 //显示缓存信息
        //显示缓存信息
 DisplayCacheInfo();
        DisplayCacheInfo();
 }
    }
 // CacheItemRemovedCallback 委托方法
    // CacheItemRemovedCallback 委托方法
 private void ItemRemoved(String key, object value, CacheItemRemovedReason removedReason)
    private void ItemRemoved(String key, object value, CacheItemRemovedReason removedReason)
 {
    {
 reason = removedReason;
        reason = removedReason;
 }
    }
 private void DisplayCacheInfo()
    private void DisplayCacheInfo()
 {
    {
 string cacheCount = Cache.Count.ToString();
        string cacheCount = Cache.Count.ToString();
 lbCacheInfo.Text = "共包括" + cacheCount + "个缓存对象:";
        lbCacheInfo.Text = "共包括" + cacheCount + "个缓存对象:";
 IDictionaryEnumerator CacheEnum = Cache.GetEnumerator();
        IDictionaryEnumerator CacheEnum = Cache.GetEnumerator();
 while (CacheEnum.MoveNext())
        while (CacheEnum.MoveNext())
 {
        {
 lbCacheInfo.Text += CacheEnum.Key.ToString() + ", ";
            lbCacheInfo.Text += CacheEnum.Key.ToString() + ", ";
 }
        }
 }
    }
 protected void Page_Load(object sender, EventArgs e)
    protected void Page_Load(object sender, EventArgs e)
 {
    {

 }
    }
 }
}
 
4 缓存依赖
包括对XML,数据库(sql server的依赖)
功能的核心是:sqlcachedependency类
  
1 缓存依赖对xml操作
把xml文件加载到界面缓存,然后进行操作
xml(Computer.xml)文件如下:
 <Hardware>
  <Hardware>
 <Item Choice="Intel" Price="1201" Url="PageA1.aspx" />
  <Item Choice="Intel" Price="1201" Url="PageA1.aspx" />
 <Item Choice="AMD" Price="852" Url="PageB1.aspx" />
  <Item Choice="AMD" Price="852" Url="PageB1.aspx" />
 </Hardware>
</Hardware>
Html界面
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm6.aspx.cs" Inherits="WebForm6" %>
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm6.aspx.cs" Inherits="WebForm6" %>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" >
 <head runat="server">
<head runat="server">
 <title>实现自定义缓存依赖</title>
     <title>实现自定义缓存依赖</title>
 <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />
    <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />
 </head>
</head>
 <body>
<body>
 <form id="form1" runat="server">
    <form id="form1" runat="server">
 <div>
    <div>
 <fieldset style="width: 300px">
    <fieldset style="width: 300px">
 <legend class="mainTitle">自定义缓存依赖应用</legend>
      <legend class="mainTitle">自定义缓存依赖应用</legend>
 <br />
      <br />
 <div class="commonText">
       <div class="commonText">
 <%--test--%>
       <%--test--%>
 <center>
                    <center>
 <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White"
                        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White"
 BorderStyle="Ridge" BorderWidth="1px" CellPadding="3" CellSpacing="1" GridLines="None"
                            BorderStyle="Ridge" BorderWidth="1px" CellPadding="3" CellSpacing="1" GridLines="None"
 Width="250px">
                            Width="250px">
 <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
 <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
                            <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
 <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
 <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
 <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
                            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
 </asp:GridView>
                        </asp:GridView>
 </center>
                    </center>
 </div>
       </div>
 
       
 
       
 <div>
       <div>
 <center>
                    <center>
 <table width="250px">
                        <table width="250px">
 <tr>
                            <tr>
 <td>
                                <td>
 Choice:<asp:TextBox ID="txtChoice" runat="server" Width="40px"></asp:TextBox></td>
                                    Choice:<asp:TextBox ID="txtChoice" runat="server" Width="40px"></asp:TextBox></td>
 <td>
                                <td>
 Price:<asp:TextBox ID="txtPrice" runat="server" Width="40px"></asp:TextBox></td>
                                    Price:<asp:TextBox ID="txtPrice" runat="server" Width="40px"></asp:TextBox></td>
 <td>
                                <td>
 Url:<asp:TextBox ID="txtUrl" runat="server" Width="40px"></asp:TextBox></td>
                                    Url:<asp:TextBox ID="txtUrl" runat="server" Width="40px"></asp:TextBox></td>
 </tr>
                            </tr>
 <tr>
                            <tr>
 <td colspan="3">
                                <td colspan="3">
 <asp:Button ID="btUpdate" Text="修改XML文件" runat="Server" OnClick="UpdateXmlFile"></asp:Button>
                                    <asp:Button ID="btUpdate" Text="修改XML文件" runat="Server" OnClick="UpdateXmlFile"></asp:Button>
 </td>
                               </td> 
 </tr>
                            </tr>
 <tr>
                            <tr>
 <td colspan=3>
                                <td colspan=3>
 <asp:Button ID="btCacheRemove" Text="缓存清除" runat=server OnClick="btCacheRemove_Click" />
                                  <asp:Button ID="btCacheRemove" Text="缓存清除" runat=server OnClick="btCacheRemove_Click" />
 
                                  
 </td>
                                </td>
 </tr>
                            </tr>
 </table>
                        </table>
 </center>
                    </center>
 <div>
                    <div>
 <hr />
                        <hr />
 <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label></div>
                        <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label></div>
 </div>
      </div>
 
                
 </fieldset>
    </fieldset> 
 </div>
    </div>
 </form>
    </form>
 </body>
</body>
 </html>
</html>
代码部分
 using System;
using System;
 using System.Data;
using System.Data;
 using System.Configuration;
using System.Configuration;
 using System.Collections;
using System.Collections;
 using System.Web;
using System.Web;
 using System.Web.Security;
using System.Web.Security;
 using System.Web.UI;
using System.Web.UI;
 using System.Web.UI.WebControls;
using System.Web.UI.WebControls;
 using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls.WebParts;
 using System.Web.UI.HtmlControls;
using System.Web.UI.HtmlControls;
 using System.Web.Caching;
using System.Web.Caching;
 using System.IO;
using System.IO;

 /*自定义缓存依赖应用*/
/*自定义缓存依赖应用*/
 public partial class WebForm6 : System.Web.UI.Page
public partial class WebForm6 : System.Web.UI.Page
 {
{

 static CacheItemRemovedReason reason;
    static CacheItemRemovedReason reason;

 protected void Page_Load(object sender, EventArgs e)
    protected void Page_Load(object sender, EventArgs e)
 {
    {
 if (!IsPostBack)
        if (!IsPostBack)
 {
        {

 LoadData();
            LoadData();
 }
        }
 }
    }

 //加载数据
    //加载数据
 private void LoadData()
    private void LoadData()
 {
    {
 DataView source;
        DataView source;
 //如果缓存为空,则添加缓存
        //如果缓存为空,则添加缓存       
 if (Cache["tempData"] == null)
        if (Cache["tempData"] == null)
 {
        {
 
            
 DataSet ds = new DataSet();
            DataSet ds = new DataSet();
 string filePath = Server.MapPath("../../App_Data/Computer.xml");
            string filePath = Server.MapPath("../../App_Data/Computer.xml");
 ds.ReadXml(filePath);
            ds.ReadXml(filePath);
 source = new DataView(ds.Tables[0]);
            source = new DataView(ds.Tables[0]);

 //
            //
 CacheDependency dep = new CacheDependency(filePath, DateTime.Now);
            CacheDependency dep = new CacheDependency(filePath, DateTime.Now);
 Cache.Insert("tempData", source, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(CacheChanged));
            Cache.Insert("tempData", source, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(CacheChanged));
 //如果缓存依赖变化,则显示有关信息
            //如果缓存依赖变化,则显示有关信息
 if (dep.HasChanged)
            if (dep.HasChanged)
 {
            {
 lbMessage.Text = ">>> 缓存对象被移除,原因是" + reason.ToString() + "<br/>";
                lbMessage.Text = ">>> 缓存对象被移除,原因是" + reason.ToString() + "<br/>";
 }
            }
 
            
 
 
 lbMessage.Text += ">>> 显示XML文件数据.<br/>";
            lbMessage.Text += ">>> 显示XML文件数据.<br/>";
 }
        }
 else
        else
 {
        {
 source = (DataView)Cache["tempData"];
            source = (DataView)Cache["tempData"];
 lbMessage.Text = ">>> 显示缓存对象中的数据.<br/>";
            lbMessage.Text = ">>> 显示缓存对象中的数据.<br/>";
 }
        }
 //实现数据绑定
        //实现数据绑定
 GridView1.DataSource = source;
        GridView1.DataSource = source;
 GridView1.DataBind();
        GridView1.DataBind();
 }
    }

 // CacheItemRemovedCallback 委托方法
    // CacheItemRemovedCallback 委托方法
 private void CacheChanged(String key, object value, CacheItemRemovedReason removedReason)
    private void CacheChanged(String key, object value, CacheItemRemovedReason removedReason)
 {
    {
 reason = removedReason;
        reason = removedReason;
 }
    }

 //实现对XMl文件的修改
    //实现对XMl文件的修改
 protected void UpdateXmlFile(object sender, EventArgs e)
    protected void UpdateXmlFile(object sender, EventArgs e)
 {
    {
 ////读取XML文件数据
        ////读取XML文件数据
 DataSet ds = new DataSet();
        DataSet ds = new DataSet();
 string filePath = Server.MapPath("../../App_Data/Computer.xml");
        string filePath = Server.MapPath("../../App_Data/Computer.xml");
 ds.ReadXml(filePath);
        ds.ReadXml(filePath);
 //添加新数据行
        //添加新数据行       
 try
        try
 {
        {
 DataRow newLine = ds.Tables[0].NewRow();
            DataRow newLine = ds.Tables[0].NewRow();
 newLine["Choice"] = txtChoice.Text;
            newLine["Choice"] = txtChoice.Text;
 newLine["Price"] = txtPrice.Text;
            newLine["Price"] = txtPrice.Text;
 newLine["Url"] = txtUrl.Text;
            newLine["Url"] = txtUrl.Text;
 ds.Tables[0].Rows.Add(newLine);
            ds.Tables[0].Rows.Add(newLine);
 }
        }
 catch
        catch
 {
        {
 lbMessage.Text = "无法正常添加新数据.<br/>";
            lbMessage.Text = "无法正常添加新数据.<br/>";
 }
        }
 //通过新建和覆盖方式,将数据写入XML文件
        //通过新建和覆盖方式,将数据写入XML文件        
 FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
        FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
 ds.WriteXml(fs);
        ds.WriteXml(fs);
 fs.Close();
        fs.Close();
 //移除缓存对象
        //移除缓存对象
 Cache.Remove("tempData");
        Cache.Remove("tempData");
 //重新加载数据
        //重新加载数据
 LoadData();
        LoadData();
 }
    }

 protected void btCacheRemove_Click(object sender, EventArgs e)
    protected void btCacheRemove_Click(object sender, EventArgs e)
 {
    {
 //缓存清除
        //缓存清除
 if (Cache["tempData"]!=null)
        if (Cache["tempData"]!=null)
 {
        {
 Cache.Remove("tempData");
            Cache.Remove("tempData"); 
 }
        }

 //Cache.Remove("tempData");
        //Cache.Remove("tempData");  

 }
    }
 }
}
 
 CREATE TABLE [dbo].[userinfo](
 CREATE TABLE [dbo].[userinfo](
 [UserId] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
    [UserId] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
 [UserName] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
    [UserName] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
 [BranchId] [varchar](4) COLLATE Chinese_PRC_CI_AS NULL,
    [BranchId] [varchar](4) COLLATE Chinese_PRC_CI_AS NULL,
 ) 
(2)对表增加数据
    ) 
(2)对表增加数据
(3)进入dos界面,输入命令
aspnet_regsql -S localhost(sql服务器名称) -U sa(用户名) -P mypassword(密码) -d CPC_BusinessDB(数据库名称) -ed -t userinfo(表名)
注意:
关闭数据库依赖
aspnet_regsql -S localhost(sql服务器名称) -U sa(用户名) -P mypassword(密码) -d CPC_BusinessDB(数据库名称) -dd
关闭数据表依赖
aspnet_regsql -S localhost(sql服务器名称) -U sa(用户名) -P mypassword(密码) -d CPC_BusinessDB(数据库名称) -t userinfo(表名) -dt
 
命令执行完成以后 在CPC_BusinessDB 下面增加 AspNet_SqlCacheTablesForChangeNotification表,显示缓存的 详细信息
(4)编写代码
web.config
 
数据库连接字符串
 <connectionStrings>
<connectionStrings>    
 <add name="LoggingDb" connectionString="user id=sa;password=XXXXXXXX;data source=JIAHAITIAN;persist security info=False;initial catalog=CPC_BusinessDB" providerName="System.Data.SqlClient"/>
    <add name="LoggingDb" connectionString="user id=sa;password=XXXXXXXX;data source=JIAHAITIAN;persist security info=False;initial catalog=CPC_BusinessDB" providerName="System.Data.SqlClient"/>
 </connectionStrings>
  </connectionStrings>
缓存设置
 <caching>
   <caching>
 
      
 <sqlCacheDependency enabled="true" pollTime="600">
      <sqlCacheDependency enabled="true" pollTime="600">
 <databases>
        <databases>
 <add name="CPC_BusinessDB" connectionStringName="LoggingDb"/>
          <add name="CPC_BusinessDB" connectionStringName="LoggingDb"/>
 </databases>
        </databases>
 </sqlCacheDependency>
      </sqlCacheDependency>
 </caching>
    </caching>
html部分
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm7.aspx.cs" Inherits="WebForm7" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm7.aspx.cs" Inherits="WebForm7" %>
 <%@ OutputCache Duration="1000"  SqlDependency="CPC_BusinessDB:userinfo" VaryByParam="none" %>
<%@ OutputCache Duration="1000"  SqlDependency="CPC_BusinessDB:userinfo" VaryByParam="none" %>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


 <html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" >
 <head runat="server">
<head runat="server">
 <title>无标题页</title>
    <title>无标题页</title>
 </head>
</head>
 <body>
<body>
 <form id="form1" runat="server">
      <form id="form1" runat="server">
 <div>
        <div>
 <fieldset style="width: 260px">
            <fieldset style="width: 260px">
 <legend class="mainTitle">SQL数据缓存依赖应用</legend>
                <legend class="mainTitle">SQL数据缓存依赖应用</legend>
 <br />
                <br />
 <div class="commonText">
                <div class="commonText">
 <center>
                    <center>
 <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White"
                        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White"
 BorderStyle="Ridge" BorderWidth="1px" CellPadding="3" CellSpacing="1" GridLines="None"
                            BorderStyle="Ridge" BorderWidth="1px" CellPadding="3" CellSpacing="1" GridLines="None"
 Width="250px" AllowPaging="True" AutoGenerateColumns="False"
                            Width="250px" AllowPaging="True" AutoGenerateColumns="False" 
 PageSize="6">
                            PageSize="6">
 <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
 <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
                            <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
 <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
 <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
 <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
                            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
 <Columns>
                            <Columns>
 <asp:BoundField DataField="userid" HeaderText="userid" ReadOnly="True" SortExpression="userid" />
                                <asp:BoundField DataField="userid" HeaderText="userid" ReadOnly="True" SortExpression="userid" />
 <asp:BoundField DataField="username" HeaderText="username"   SortExpression="username"/>
                                <asp:BoundField DataField="username" HeaderText="username"   SortExpression="username"/>
 <asp:BoundField DataField="branchid" HeaderText="branchid"   SortExpression="branchid" />
                                <asp:BoundField DataField="branchid" HeaderText="branchid"   SortExpression="branchid" />
 </Columns>
                            </Columns>
 </asp:GridView>
                        </asp:GridView>
 
                       
 </center>
                    </center>
 </div>
                </div>
 <div>
                <div>
 <center>
                    <center>
 <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label> </center>
                        <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label> </center>
 </div>
                </div>
 </fieldset>
            </fieldset>
 </div>
        </div>
 </form>
    </form>
 </body>
</body>
 </html>
</html>
代码部分
 using System;
using System;
 using System.Data;
using System.Data;
 using System.Configuration;
using System.Configuration;
 using System.Collections;
using System.Collections;
 using System.Web;
using System.Web;
 using System.Web.Security;
using System.Web.Security;
 using System.Web.UI;
using System.Web.UI;
 using System.Web.UI.WebControls;
using System.Web.UI.WebControls;
 using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls.WebParts;
 using System.Web.UI.HtmlControls;
using System.Web.UI.HtmlControls;
 using System.Data.SqlClient;
using System.Data.SqlClient;

 public partial class WebForm7 : System.Web.UI.Page
public partial class WebForm7 : System.Web.UI.Page
 {
{
 protected void Page_Load(object sender, EventArgs e)
    protected void Page_Load(object sender, EventArgs e)
 {
    {
 lbMessage.Text = "页面刷新时间:" + DateTime.Now.ToString();
        lbMessage.Text = "页面刷新时间:" + DateTime.Now.ToString();
 bind_data();
        bind_data();
 }
    }

 private void bind_data()
    private void bind_data()
 {
    {
 
        
 string str_Conn = "user id=sa;password=19791225;data source=JIAHAITIAN;persist security info=False;initial catalog=CPC_BusinessDB";
        string str_Conn = "user id=sa;password=19791225;data source=JIAHAITIAN;persist security info=False;initial catalog=CPC_BusinessDB";
 try
        try
 {
        {
 DataSet ds=new DataSet() ;
            DataSet ds=new DataSet() ;
 SqlConnection objConn = new SqlConnection(str_Conn);
            SqlConnection objConn = new SqlConnection(str_Conn);
 //objConn.Open();
            //objConn.Open();

 string str_sql = "select userid,username,branchid from userinfo";
            string str_sql = "select userid,username,branchid from userinfo";
 SqlCommand objComm = new SqlCommand(str_sql, objConn);
            SqlCommand objComm = new SqlCommand(str_sql, objConn);
 SqlDataAdapter objAdapter = new SqlDataAdapter(objComm);
            SqlDataAdapter objAdapter = new SqlDataAdapter(objComm);
 objAdapter.Fill(ds, "userinfo");
            objAdapter.Fill(ds, "userinfo");
 GridView1.DataSource = ds.Tables[0];
            GridView1.DataSource = ds.Tables[0];
 GridView1.DataBind();
            GridView1.DataBind();
 //objConn.Close();
            //objConn.Close();
 }
        }
 catch (Exception exc)
        catch (Exception exc)
 {
        {
 //MessageBox.Show(exc.Message);
            //MessageBox.Show(exc.Message);

 }
        }



 }
    }

 }
}
 
这样实现SQL数据缓存依赖
StyleSheet.css 文件
 body
body
 {
{
 }
}
 .mainTitle
.mainTitle
 {
{
 font-size: 12pt;
    font-size: 12pt;
 font-weight: bold;
    font-weight: bold;
 font-family: 宋体;
    font-family: 宋体;
 }
}
 .commonText
.commonText
 {
{
 font-size: 10pt;
    font-size: 10pt;
 font-family: 宋体;
    font-family: 宋体;
 }
}
 .littleMainTitle
.littleMainTitle
 {
{
 font-size: 10pt;
    font-size: 10pt;
 font-weight: bold;
    font-weight: bold;
 font-family: 宋体;
    font-family: 宋体;
 }
}
 
1 页面输出缓存
页面输出缓存是将页面全部内容都保存在内存中,并用于完成客户端请求
点击超连接,读入参数location=beijing ,页面每隔5秒刷新一次
HTML部分
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm3.aspx.cs" Inherits="WebForm3" %>
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm3.aspx.cs" Inherits="WebForm3" %> <%@ OutputCache Duration ="5" VaryByParam="location"  %>
<%@ OutputCache Duration ="5" VaryByParam="location"  %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server">
<head id="Head1" runat="server"> <title>页面缓存应用1</title>
    <title>页面缓存应用1</title> <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />
    <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />     </head>
</head> <body>
<body> <form id="form1" runat="server">
    <form id="form1" runat="server"> <div>
        <div> <fieldset style="width: 240px">
            <fieldset style="width: 240px"> <legend class="mainTitle">设置页面输出缓存</legend>
                <legend class="mainTitle">设置页面输出缓存</legend> <br />
                <br /> <center>
                <center> <asp:Label ID="Label1" runat="server" CssClass="commonText"></asp:Label></center>
                    <asp:Label ID="Label1" runat="server" CssClass="commonText"></asp:Label></center> <br />
                <br /> <a href="WebForm3.aspx?location=beijing" class="littleMainTitle">缓存时间</a><br />
                    <a href="WebForm3.aspx?location=beijing" class="littleMainTitle">缓存时间</a><br /> </fieldset>
            </fieldset> </div>
        </div> </form>
    </form> </body>
</body> </html>
</html> protected void Page_Load(object sender, EventArgs e)
  protected void Page_Load(object sender, EventArgs e) {
    { /*
        /* * 页面缓存
         * 页面缓存 * 应用程序初始显示 的是停止执行缓存的时间,当用户刷新页面时,时间将随时变化
         * 应用程序初始显示 的是停止执行缓存的时间,当用户刷新页面时,时间将随时变化 * 单击"缓存时间超连接以后,页面重新定位,这时页面显示时间被缓存,数据过期时间为5秒,如果不断刷新该页面,那么每隔5秒刷新一次
         * 单击"缓存时间超连接以后,页面重新定位,这时页面显示时间被缓存,数据过期时间为5秒,如果不断刷新该页面,那么每隔5秒刷新一次 */
         */ 
       //设置仅将缓存数据存储在服务器上
            //设置仅将缓存数据存储在服务器上 Response.Cache.SetCacheability(HttpCacheability.Server);
            Response.Cache.SetCacheability(HttpCacheability.Server); string temp_location = Request.QueryString["location"];
            string temp_location = Request.QueryString["location"]; //如果location为空,则不缓存,否则根据@ OutputCache指令声明执行缓存
            //如果location为空,则不缓存,否则根据@ OutputCache指令声明执行缓存 if (temp_location == null)
            if (temp_location == null) {
            { //停止当前响应的所有服务器缓存
                //停止当前响应的所有服务器缓存 Response.Cache.SetNoServerCaching();
                Response.Cache.SetNoServerCaching(); Label1.Text = "停止缓存的时间:" + DateTime.Now.ToString();
                Label1.Text = "停止缓存的时间:" + DateTime.Now.ToString(); }
            } else
            else {
            { Label1.Text = "设置了缓存的时间:" + DateTime.Now.ToString();
                Label1.Text = "设置了缓存的时间:" + DateTime.Now.ToString(); }
            } 
       
         }
    } 
    实现方式: 控件缓存和缓存后替换
控件缓存:允许将需要缓存的信息包含在一个用户控件内,然后将该控件标记为可缓存的,以此来缓存页面输出的部分内容
缓存后替换,使用缓存后替换机制,可以将页配置为进行缓存,将页的个别部分标记为不可缓存.
将整个页面输出缓存,然后实现缓存后替代
HTML部分
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm4.aspx.cs" Inherits="WebForm4" %>
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm4.aspx.cs" Inherits="WebForm4" %>
 <%@ OutputCache Duration="10" VaryByParam="None" %>
<%@ OutputCache Duration="10" VaryByParam="None" %>

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<head runat="server"> <title>无标题页</title>
    <title>无标题页</title> </head>
</head> <body>
<body> <form id="form1" runat="server">
   <form id="form1" runat="server"> <div>
        <div> <fieldset style="width: 320px">
            <fieldset style="width: 320px"> <legend class="mainTitle">使用Substitution控件实现页面部分缓存</legend>
              <legend class="mainTitle">使用Substitution控件实现页面部分缓存</legend> <br />
              <br /> <div class="littleMainTitle">
                <div class="littleMainTitle"> 以下时间显示使用Substitution控件实现缓存后替换:</div>
                    以下时间显示使用Substitution控件实现缓存后替换:</div> <asp:Substitution ID="Substitution2" MethodName="GetCurrentDateTime" runat="Server">
                <asp:Substitution ID="Substitution2" MethodName="GetCurrentDateTime" runat="Server"> </asp:Substitution>
                      </asp:Substitution> 
                <hr />
                 <hr /> <div class="littleMainTitle">
                  <div class="littleMainTitle"> 以下时间显示使用页面输出缓存,缓存时间为5秒:</div>
                    以下时间显示使用页面输出缓存,缓存时间为5秒:</div> <asp:Label ID="CachedDateLabel" runat="Server"></asp:Label>
                    <asp:Label ID="CachedDateLabel" runat="Server"></asp:Label> <br />
                     <br /> <center>
                <center> <asp:Button ID="RefreshButton" Text="刷新页面" runat="Server"></asp:Button></center>
                <asp:Button ID="RefreshButton" Text="刷新页面" runat="Server"></asp:Button></center> 
                 <hr />
                <hr /> <br>
                <br> <div class="littleMainTitle">
                <div class="littleMainTitle"> 以下时间显示使用Substitution控件API实现缓存后替换:</div>
                    以下时间显示使用Substitution控件API实现缓存后替换:</div> <%Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetCurrentDateTime)); %>
                <%Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetCurrentDateTime)); %> 
                 
                 </fieldset>
            </fieldset> </div>
        </div> </form>
    </form> </body>
</body> </html>
</html>代码部分
 protected void Page_Load(object sender, EventArgs e)
 protected void Page_Load(object sender, EventArgs e) {
    { CachedDateLabel.Text = DateTime.Now.ToString();
        CachedDateLabel.Text = DateTime.Now.ToString(); }
    } public static string GetCurrentDateTime(HttpContext context)
    public static string GetCurrentDateTime(HttpContext context) {
    { return DateTime.Now.ToString();
        return DateTime.Now.ToString(); }
    }这里把整个页面设置为页面缓存,然后
<asp:Substitution ID="Substitution2" MethodName="GetCurrentDateTime" runat="Server">
</asp:Substitution>
和
<%Response.WriteSubstitution(new HttpResponseSubstitutionCallback(GetCurrentDateTime)); %>
实现了缓存替换
3 应用程序数据缓存
提供了一种编程方式,可以通过键/值方式对将任意数据存储在内存中.
应用程序缓存的主要功能是在内存中存储各种与应用程序相关的对象
优点 :由asp.net管理缓存,他会在项过期,无效,或内存不足的时候移除缓存中的项,还可以配置应用程序缓存,以便在移除项的时候通知
应用程序实现对缓存的增加,删除,检索
对字符串数组tempArray进行操作,保存到数据缓存里面
html代码
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm5.aspx.cs" Inherits="WebForm5" %>
  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm5.aspx.cs" Inherits="WebForm5" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<head runat="server"> <title>应用程序数据缓存</title>
     <title>应用程序数据缓存</title> <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />
    <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" /> </head>
</head> <body>
<body> <form id="form1" runat="server">
    <form id="form1" runat="server"> <div>
        <div> <fieldset style="width: 310px">
            <fieldset style="width: 310px"> <legend class="mainTitle">实现应用程序数据缓存</legend>
                <legend class="mainTitle">实现应用程序数据缓存</legend> <br />
                <br /> <div class="commonText">
                <div class="commonText"> 字符串数组内容如下:</div>
                    字符串数组内容如下:</div> <div class="commonText" align="center">
                <div class="commonText" align="center"> 北京,上海,广州,成都,深圳</div>
                    北京,上海,广州,成都,深圳</div> <hr />
                <hr /> <div>
                <div> <center>
                    <center> <asp:Button ID="btAdd" Text="添加" runat="Server" OnClick="AddItemToCache"></asp:Button>
                        <asp:Button ID="btAdd" Text="添加" runat="Server" OnClick="AddItemToCache"></asp:Button> <asp:Button ID="btGet" Text="检索" runat="Server" OnClick="GetItemFromCache"></asp:Button>
                        <asp:Button ID="btGet" Text="检索" runat="Server" OnClick="GetItemFromCache"></asp:Button> <asp:Button ID="btDel" Text="移除" runat="Server" OnClick="RemoveItemFromCache"></asp:Button>
                        <asp:Button ID="btDel" Text="移除" runat="Server" OnClick="RemoveItemFromCache"></asp:Button> <div>
                        <div> <asp:Label ID="lbCacheInfo" runat="server" CssClass="commonText" ForeColor="red"></asp:Label></div>
                            <asp:Label ID="lbCacheInfo" runat="server" CssClass="commonText" ForeColor="red"></asp:Label></div> </center>
                    </center> </div>
                </div> <hr />
                <hr /> <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label>
                <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label> </fieldset>
            </fieldset> </div>
        </div> </form>
    </form> </body>
</body> </html>
</html>代码部分
 using System;
using System; using System.Data;
using System.Data; using System.Configuration;
using System.Configuration; using System.Collections;
using System.Collections; using System.Web;
using System.Web; using System.Web.Security;
using System.Web.Security; using System.Web.UI;
using System.Web.UI; using System.Web.UI.WebControls;
using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
using System.Web.UI.HtmlControls; using System.Web.Caching;
using System.Web.Caching;
 public partial class WebForm5 : System.Web.UI.Page
public partial class WebForm5 : System.Web.UI.Page {
{
 //声明变量
    //声明变量     static CacheItemRemovedReason reason;
    static CacheItemRemovedReason reason; string[] tempArray = { "北京", "上海", "广州", "成都", "深圳" };
    string[] tempArray = { "北京", "上海", "广州", "成都", "深圳" }; //实现添加按钮的事件处理程序
    //实现添加按钮的事件处理程序 protected void AddItemToCache(object sender, EventArgs e)
    protected void AddItemToCache(object sender, EventArgs e) {
    { //如果不存在,则添加;否则,只显示有关信息
        //如果不存在,则添加;否则,只显示有关信息 if (Cache["tempArray"] == null)
        if (Cache["tempArray"] == null) {
        { Cache.Add("tempArray", tempArray, null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(ItemRemoved));
            Cache.Add("tempArray", tempArray, null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(ItemRemoved)); lbMessage.Text += ">>>已经将字符串数组添加到缓存中 <br/>";
            lbMessage.Text += ">>>已经将字符串数组添加到缓存中 <br/>"; }
        } else
        else {
        { lbMessage.Text += ">>>缓存中已经存在字符串数组 <br/>";
            lbMessage.Text += ">>>缓存中已经存在字符串数组 <br/>"; }
        } //显示缓存信息
        //显示缓存信息 DisplayCacheInfo();
        DisplayCacheInfo(); }
    } //实现检索按钮的事件处理程序
    //实现检索按钮的事件处理程序 protected void GetItemFromCache(object sender, EventArgs e)
    protected void GetItemFromCache(object sender, EventArgs e) {
    { //根据是否存在,显示信息
        //根据是否存在,显示信息 if (Cache["tempArray"] != null)
        if (Cache["tempArray"] != null) {
        { lbMessage.Text += ">>>已检索到缓存中包括字符串数组 <br/>";
            lbMessage.Text += ">>>已检索到缓存中包括字符串数组 <br/>"; }
        } else
        else {
        { lbMessage.Text += ">>>未检索到缓存中包括字符串数组 <br/>";
            lbMessage.Text += ">>>未检索到缓存中包括字符串数组 <br/>"; }
        } //显示缓存信息
        //显示缓存信息 DisplayCacheInfo();
        DisplayCacheInfo(); }
    } //实现删除按钮的事件处理程序
    //实现删除按钮的事件处理程序 protected void RemoveItemFromCache(object sender, EventArgs e)
    protected void RemoveItemFromCache(object sender, EventArgs e) {
    { //如果不存在,则显示信息;否则,调用方法移除
        //如果不存在,则显示信息;否则,调用方法移除 if (Cache["tempArray"] == null)
        if (Cache["tempArray"] == null) {
        { lbMessage.Text += ">>>未缓存字符串数组,无法删除<br/>";
            lbMessage.Text += ">>>未缓存字符串数组,无法删除<br/>"; }
        } else
        else {
        { Cache.Remove("tempArray");
            Cache.Remove("tempArray"); lbMessage.Text += ">>>已经调用 CacheItemRemovedCallback 委托方法,缓存移除原因是:" + reason.ToString() + "<br/>";
            lbMessage.Text += ">>>已经调用 CacheItemRemovedCallback 委托方法,缓存移除原因是:" + reason.ToString() + "<br/>"; lbMessage.Text += ">>>已删除字符串数组缓存<br/>";
            lbMessage.Text += ">>>已删除字符串数组缓存<br/>"; }
        } //显示缓存信息
        //显示缓存信息 DisplayCacheInfo();
        DisplayCacheInfo(); }
    } // CacheItemRemovedCallback 委托方法
    // CacheItemRemovedCallback 委托方法 private void ItemRemoved(String key, object value, CacheItemRemovedReason removedReason)
    private void ItemRemoved(String key, object value, CacheItemRemovedReason removedReason) {
    { reason = removedReason;
        reason = removedReason; }
    } private void DisplayCacheInfo()
    private void DisplayCacheInfo() {
    { string cacheCount = Cache.Count.ToString();
        string cacheCount = Cache.Count.ToString(); lbCacheInfo.Text = "共包括" + cacheCount + "个缓存对象:";
        lbCacheInfo.Text = "共包括" + cacheCount + "个缓存对象:"; IDictionaryEnumerator CacheEnum = Cache.GetEnumerator();
        IDictionaryEnumerator CacheEnum = Cache.GetEnumerator(); while (CacheEnum.MoveNext())
        while (CacheEnum.MoveNext()) {
        { lbCacheInfo.Text += CacheEnum.Key.ToString() + ", ";
            lbCacheInfo.Text += CacheEnum.Key.ToString() + ", "; }
        } }
    } protected void Page_Load(object sender, EventArgs e)
    protected void Page_Load(object sender, EventArgs e) {
    {
 }
    } }
}4 缓存依赖
包括对XML,数据库(sql server的依赖)
功能的核心是:sqlcachedependency类
1 缓存依赖对xml操作
把xml文件加载到界面缓存,然后进行操作
xml(Computer.xml)文件如下:
 <Hardware>
  <Hardware> <Item Choice="Intel" Price="1201" Url="PageA1.aspx" />
  <Item Choice="Intel" Price="1201" Url="PageA1.aspx" /> <Item Choice="AMD" Price="852" Url="PageB1.aspx" />
  <Item Choice="AMD" Price="852" Url="PageB1.aspx" /> </Hardware>
</Hardware>Html界面
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm6.aspx.cs" Inherits="WebForm6" %>
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm6.aspx.cs" Inherits="WebForm6" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<head runat="server"> <title>实现自定义缓存依赖</title>
     <title>实现自定义缓存依赖</title> <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" />
    <link id="InstanceStyle" href="StyleSheet.css" type="text/css" rel="stylesheet" /> </head>
</head> <body>
<body> <form id="form1" runat="server">
    <form id="form1" runat="server"> <div>
    <div> <fieldset style="width: 300px">
    <fieldset style="width: 300px"> <legend class="mainTitle">自定义缓存依赖应用</legend>
      <legend class="mainTitle">自定义缓存依赖应用</legend> <br />
      <br /> <div class="commonText">
       <div class="commonText"> <%--test--%>
       <%--test--%> <center>
                    <center> <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White"
                        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="1px" CellPadding="3" CellSpacing="1" GridLines="None"
                            BorderStyle="Ridge" BorderWidth="1px" CellPadding="3" CellSpacing="1" GridLines="None" Width="250px">
                            Width="250px"> <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" /> <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
                            <RowStyle BackColor="#DEDFDE" ForeColor="Black" /> <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" /> <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
                            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" /> </asp:GridView>
                        </asp:GridView> </center>
                    </center> </div>
       </div> 
        
        <div>
       <div> <center>
                    <center> <table width="250px">
                        <table width="250px"> <tr>
                            <tr> <td>
                                <td> Choice:<asp:TextBox ID="txtChoice" runat="server" Width="40px"></asp:TextBox></td>
                                    Choice:<asp:TextBox ID="txtChoice" runat="server" Width="40px"></asp:TextBox></td> <td>
                                <td> Price:<asp:TextBox ID="txtPrice" runat="server" Width="40px"></asp:TextBox></td>
                                    Price:<asp:TextBox ID="txtPrice" runat="server" Width="40px"></asp:TextBox></td> <td>
                                <td> Url:<asp:TextBox ID="txtUrl" runat="server" Width="40px"></asp:TextBox></td>
                                    Url:<asp:TextBox ID="txtUrl" runat="server" Width="40px"></asp:TextBox></td> </tr>
                            </tr> <tr>
                            <tr> <td colspan="3">
                                <td colspan="3"> <asp:Button ID="btUpdate" Text="修改XML文件" runat="Server" OnClick="UpdateXmlFile"></asp:Button>
                                    <asp:Button ID="btUpdate" Text="修改XML文件" runat="Server" OnClick="UpdateXmlFile"></asp:Button> </td>
                               </td>  </tr>
                            </tr> <tr>
                            <tr> <td colspan=3>
                                <td colspan=3> <asp:Button ID="btCacheRemove" Text="缓存清除" runat=server OnClick="btCacheRemove_Click" />
                                  <asp:Button ID="btCacheRemove" Text="缓存清除" runat=server OnClick="btCacheRemove_Click" /> 
                                   </td>
                                </td> </tr>
                            </tr> </table>
                        </table> </center>
                    </center> <div>
                    <div> <hr />
                        <hr /> <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label></div>
                        <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label></div> </div>
      </div> 
                 </fieldset>
    </fieldset>  </div>
    </div> </form>
    </form> </body>
</body> </html>
</html>代码部分
 using System;
using System; using System.Data;
using System.Data; using System.Configuration;
using System.Configuration; using System.Collections;
using System.Collections; using System.Web;
using System.Web; using System.Web.Security;
using System.Web.Security; using System.Web.UI;
using System.Web.UI; using System.Web.UI.WebControls;
using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
using System.Web.UI.HtmlControls; using System.Web.Caching;
using System.Web.Caching; using System.IO;
using System.IO;
 /*自定义缓存依赖应用*/
/*自定义缓存依赖应用*/ public partial class WebForm6 : System.Web.UI.Page
public partial class WebForm6 : System.Web.UI.Page {
{
 static CacheItemRemovedReason reason;
    static CacheItemRemovedReason reason;
 protected void Page_Load(object sender, EventArgs e)
    protected void Page_Load(object sender, EventArgs e) {
    { if (!IsPostBack)
        if (!IsPostBack) {
        {
 LoadData();
            LoadData(); }
        } }
    }
 //加载数据
    //加载数据 private void LoadData()
    private void LoadData() {
    { DataView source;
        DataView source; //如果缓存为空,则添加缓存
        //如果缓存为空,则添加缓存        if (Cache["tempData"] == null)
        if (Cache["tempData"] == null) {
        { 
             DataSet ds = new DataSet();
            DataSet ds = new DataSet(); string filePath = Server.MapPath("../../App_Data/Computer.xml");
            string filePath = Server.MapPath("../../App_Data/Computer.xml"); ds.ReadXml(filePath);
            ds.ReadXml(filePath); source = new DataView(ds.Tables[0]);
            source = new DataView(ds.Tables[0]);
 //
            // CacheDependency dep = new CacheDependency(filePath, DateTime.Now);
            CacheDependency dep = new CacheDependency(filePath, DateTime.Now); Cache.Insert("tempData", source, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(CacheChanged));
            Cache.Insert("tempData", source, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.Default, new CacheItemRemovedCallback(CacheChanged)); //如果缓存依赖变化,则显示有关信息
            //如果缓存依赖变化,则显示有关信息 if (dep.HasChanged)
            if (dep.HasChanged) {
            { lbMessage.Text = ">>> 缓存对象被移除,原因是" + reason.ToString() + "<br/>";
                lbMessage.Text = ">>> 缓存对象被移除,原因是" + reason.ToString() + "<br/>"; }
            } 
             
  lbMessage.Text += ">>> 显示XML文件数据.<br/>";
            lbMessage.Text += ">>> 显示XML文件数据.<br/>"; }
        } else
        else {
        { source = (DataView)Cache["tempData"];
            source = (DataView)Cache["tempData"]; lbMessage.Text = ">>> 显示缓存对象中的数据.<br/>";
            lbMessage.Text = ">>> 显示缓存对象中的数据.<br/>"; }
        } //实现数据绑定
        //实现数据绑定 GridView1.DataSource = source;
        GridView1.DataSource = source; GridView1.DataBind();
        GridView1.DataBind(); }
    }
 // CacheItemRemovedCallback 委托方法
    // CacheItemRemovedCallback 委托方法 private void CacheChanged(String key, object value, CacheItemRemovedReason removedReason)
    private void CacheChanged(String key, object value, CacheItemRemovedReason removedReason) {
    { reason = removedReason;
        reason = removedReason; }
    }
 //实现对XMl文件的修改
    //实现对XMl文件的修改 protected void UpdateXmlFile(object sender, EventArgs e)
    protected void UpdateXmlFile(object sender, EventArgs e) {
    { ////读取XML文件数据
        ////读取XML文件数据 DataSet ds = new DataSet();
        DataSet ds = new DataSet(); string filePath = Server.MapPath("../../App_Data/Computer.xml");
        string filePath = Server.MapPath("../../App_Data/Computer.xml"); ds.ReadXml(filePath);
        ds.ReadXml(filePath); //添加新数据行
        //添加新数据行        try
        try {
        { DataRow newLine = ds.Tables[0].NewRow();
            DataRow newLine = ds.Tables[0].NewRow(); newLine["Choice"] = txtChoice.Text;
            newLine["Choice"] = txtChoice.Text; newLine["Price"] = txtPrice.Text;
            newLine["Price"] = txtPrice.Text; newLine["Url"] = txtUrl.Text;
            newLine["Url"] = txtUrl.Text; ds.Tables[0].Rows.Add(newLine);
            ds.Tables[0].Rows.Add(newLine); }
        } catch
        catch {
        { lbMessage.Text = "无法正常添加新数据.<br/>";
            lbMessage.Text = "无法正常添加新数据.<br/>"; }
        } //通过新建和覆盖方式,将数据写入XML文件
        //通过新建和覆盖方式,将数据写入XML文件         FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
        FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); ds.WriteXml(fs);
        ds.WriteXml(fs); fs.Close();
        fs.Close(); //移除缓存对象
        //移除缓存对象 Cache.Remove("tempData");
        Cache.Remove("tempData"); //重新加载数据
        //重新加载数据 LoadData();
        LoadData(); }
    }
 protected void btCacheRemove_Click(object sender, EventArgs e)
    protected void btCacheRemove_Click(object sender, EventArgs e) {
    { //缓存清除
        //缓存清除 if (Cache["tempData"]!=null)
        if (Cache["tempData"]!=null) {
        { Cache.Remove("tempData");
            Cache.Remove("tempData");  }
        }
 //Cache.Remove("tempData");
        //Cache.Remove("tempData");  
 }
    } }
}
在 Page_设置断点,就可以看到xml加载缓存的效果
  2 缓存依赖对sql server操作
    把数据表加载到界面,然后查看,缓存更新
    (1)在数据库CPC_BusinessDB建立表 userinfo
 CREATE TABLE [dbo].[userinfo](
 CREATE TABLE [dbo].[userinfo]( [UserId] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL,
    [UserId] [varchar](8) COLLATE Chinese_PRC_CI_AS NOT NULL, [UserName] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL,
    [UserName] [varchar](20) COLLATE Chinese_PRC_CI_AS NULL, [BranchId] [varchar](4) COLLATE Chinese_PRC_CI_AS NULL,
    [BranchId] [varchar](4) COLLATE Chinese_PRC_CI_AS NULL, )
    ) (3)进入dos界面,输入命令
aspnet_regsql -S localhost(sql服务器名称) -U sa(用户名) -P mypassword(密码) -d CPC_BusinessDB(数据库名称) -ed -t userinfo(表名)
注意:
关闭数据库依赖
aspnet_regsql -S localhost(sql服务器名称) -U sa(用户名) -P mypassword(密码) -d CPC_BusinessDB(数据库名称) -dd
关闭数据表依赖
aspnet_regsql -S localhost(sql服务器名称) -U sa(用户名) -P mypassword(密码) -d CPC_BusinessDB(数据库名称) -t userinfo(表名) -dt
命令执行完成以后 在CPC_BusinessDB 下面增加 AspNet_SqlCacheTablesForChangeNotification表,显示缓存的 详细信息
(4)编写代码
web.config
数据库连接字符串
 <connectionStrings>
<connectionStrings>     <add name="LoggingDb" connectionString="user id=sa;password=XXXXXXXX;data source=JIAHAITIAN;persist security info=False;initial catalog=CPC_BusinessDB" providerName="System.Data.SqlClient"/>
    <add name="LoggingDb" connectionString="user id=sa;password=XXXXXXXX;data source=JIAHAITIAN;persist security info=False;initial catalog=CPC_BusinessDB" providerName="System.Data.SqlClient"/> </connectionStrings>
  </connectionStrings>缓存设置
 <caching>
   <caching> 
       <sqlCacheDependency enabled="true" pollTime="600">
      <sqlCacheDependency enabled="true" pollTime="600"> <databases>
        <databases> <add name="CPC_BusinessDB" connectionStringName="LoggingDb"/>
          <add name="CPC_BusinessDB" connectionStringName="LoggingDb"/> </databases>
        </databases> </sqlCacheDependency>
      </sqlCacheDependency> </caching>
    </caching>html部分
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm7.aspx.cs" Inherits="WebForm7" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebForm7.aspx.cs" Inherits="WebForm7" %> <%@ OutputCache Duration="1000"  SqlDependency="CPC_BusinessDB:userinfo" VaryByParam="none" %>
<%@ OutputCache Duration="1000"  SqlDependency="CPC_BusinessDB:userinfo" VaryByParam="none" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <html xmlns="http://www.w3.org/1999/xhtml" >
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">
<head runat="server"> <title>无标题页</title>
    <title>无标题页</title> </head>
</head> <body>
<body> <form id="form1" runat="server">
      <form id="form1" runat="server"> <div>
        <div> <fieldset style="width: 260px">
            <fieldset style="width: 260px"> <legend class="mainTitle">SQL数据缓存依赖应用</legend>
                <legend class="mainTitle">SQL数据缓存依赖应用</legend> <br />
                <br /> <div class="commonText">
                <div class="commonText"> <center>
                    <center> <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White"
                        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="1px" CellPadding="3" CellSpacing="1" GridLines="None"
                            BorderStyle="Ridge" BorderWidth="1px" CellPadding="3" CellSpacing="1" GridLines="None" Width="250px" AllowPaging="True" AutoGenerateColumns="False"
                            Width="250px" AllowPaging="True" AutoGenerateColumns="False"  PageSize="6">
                            PageSize="6"> <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" /> <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
                            <RowStyle BackColor="#DEDFDE" ForeColor="Black" /> <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" /> <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
                            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" /> <Columns>
                            <Columns> <asp:BoundField DataField="userid" HeaderText="userid" ReadOnly="True" SortExpression="userid" />
                                <asp:BoundField DataField="userid" HeaderText="userid" ReadOnly="True" SortExpression="userid" /> <asp:BoundField DataField="username" HeaderText="username"   SortExpression="username"/>
                                <asp:BoundField DataField="username" HeaderText="username"   SortExpression="username"/> <asp:BoundField DataField="branchid" HeaderText="branchid"   SortExpression="branchid" />
                                <asp:BoundField DataField="branchid" HeaderText="branchid"   SortExpression="branchid" /> </Columns>
                            </Columns> </asp:GridView>
                        </asp:GridView> 
                        </center>
                    </center> </div>
                </div> <div>
                <div> <center>
                    <center> <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label> </center>
                        <asp:Label ID="lbMessage" runat="server" CssClass="commonText" ForeColor="blue"></asp:Label> </center> </div>
                </div> </fieldset>
            </fieldset> </div>
        </div> </form>
    </form> </body>
</body> </html>
</html>代码部分
 using System;
using System; using System.Data;
using System.Data; using System.Configuration;
using System.Configuration; using System.Collections;
using System.Collections; using System.Web;
using System.Web; using System.Web.Security;
using System.Web.Security; using System.Web.UI;
using System.Web.UI; using System.Web.UI.WebControls;
using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
using System.Web.UI.HtmlControls; using System.Data.SqlClient;
using System.Data.SqlClient;
 public partial class WebForm7 : System.Web.UI.Page
public partial class WebForm7 : System.Web.UI.Page {
{ protected void Page_Load(object sender, EventArgs e)
    protected void Page_Load(object sender, EventArgs e) {
    { lbMessage.Text = "页面刷新时间:" + DateTime.Now.ToString();
        lbMessage.Text = "页面刷新时间:" + DateTime.Now.ToString(); bind_data();
        bind_data(); }
    }
 private void bind_data()
    private void bind_data() {
    { 
         string str_Conn = "user id=sa;password=19791225;data source=JIAHAITIAN;persist security info=False;initial catalog=CPC_BusinessDB";
        string str_Conn = "user id=sa;password=19791225;data source=JIAHAITIAN;persist security info=False;initial catalog=CPC_BusinessDB"; try
        try {
        { DataSet ds=new DataSet() ;
            DataSet ds=new DataSet() ; SqlConnection objConn = new SqlConnection(str_Conn);
            SqlConnection objConn = new SqlConnection(str_Conn); //objConn.Open();
            //objConn.Open();
 string str_sql = "select userid,username,branchid from userinfo";
            string str_sql = "select userid,username,branchid from userinfo"; SqlCommand objComm = new SqlCommand(str_sql, objConn);
            SqlCommand objComm = new SqlCommand(str_sql, objConn); SqlDataAdapter objAdapter = new SqlDataAdapter(objComm);
            SqlDataAdapter objAdapter = new SqlDataAdapter(objComm); objAdapter.Fill(ds, "userinfo");
            objAdapter.Fill(ds, "userinfo"); GridView1.DataSource = ds.Tables[0];
            GridView1.DataSource = ds.Tables[0]; GridView1.DataBind();
            GridView1.DataBind(); //objConn.Close();
            //objConn.Close(); }
        } catch (Exception exc)
        catch (Exception exc) {
        { //MessageBox.Show(exc.Message);
            //MessageBox.Show(exc.Message);
 }
        }


 }
    }
 }
}
这样实现SQL数据缓存依赖
StyleSheet.css 文件
 body
body {
{ }
} .mainTitle
.mainTitle {
{ font-size: 12pt;
    font-size: 12pt; font-weight: bold;
    font-weight: bold; font-family: 宋体;
    font-family: 宋体; }
} .commonText
.commonText {
{ font-size: 10pt;
    font-size: 10pt; font-family: 宋体;
    font-family: 宋体; }
} .littleMainTitle
.littleMainTitle {
{ font-size: 10pt;
    font-size: 10pt; font-weight: bold;
    font-weight: bold; font-family: 宋体;
    font-family: 宋体; }
}
 
                    
                

 
     
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号