编程经验:高性能.NET WEB开发(3)--控件缓存

来源:互联网 发布:老摄像头改网络摄像头 编辑:程序博客网 时间:2024/06/06 14:16
 

ASP.NET: clear user control output cache(控件缓存)

1、 Web.config

 

  <appSettings>

    <add key="cacheKey"  value="myCacheKey1,myCacheKey2"/>

  </appSettings>

在大量的用户控件或者调用同一个控件的时候,我们就给控件一个属性ClassId,然后WebConfigvalue的值就枚举ClassIdOK了。

 

2、 全局应用程序类Global.asax

CanYouLib.Common.Config这个是一个自定义类方法,取Webconfig的某个key有关的value值。

这里是必须的,如果后台没有改变(没有insert,update,delete等等事件),页面的操作都会重新请求控件的内容。

  string[] pCacheKey = CanYouLib.Common.Config.GetSetting("cacheKey").Split(',');

  for (int i = 0; i < pCacheKey.Length; i++)

  {

      HttpRuntime.Cache.Insert(pCacheKey[i], DateTime.Now);

  }

 

3、 WebUserControl(自定义控件)

这里我把Page_Load都是写在页面,写在后台都是一样的。

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

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)

    {

        String[] dependencyKey = new String[1];

        dependencyKey[0] = "myCacheKey1"; //这里就是webconfigkey="cacheKey"其中的value

        BasePartialCachingControl pcc = Parent as BasePartialCachingControl;

        if(pcc != null)

         pcc.Dependency = new CacheDependency(null, dependencyKey);

    }

</script>

 

4、  进入引起某个key="cacheKey"value事件(数据更新等等)里面

 

<script runat="server">

    protected void Button2_Click(object sender, EventArgs e)

    {

        Cache.Insert("myCacheKey", DateTime.Now);

    }

</script>

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title>控件缓存</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <uc1:WebUserControl ID="WebUserControl1" runat="server"></uc1:WebUserControl>

    </div>

    <div>

        <asp:Button ID="Button1" runat="server" Text="Cause a postback(导致回发)" />

        <asp:Button ID="Button2" runat="server" Text="Remove from cache(清除缓存)" OnClick="Button2_Click" />

    </div>

    </form>

</body>

</html>

 

关键就是在相应的事件的地方,加个Cache.Insert("myCacheKey", DateTime.Now);

 

 

相关文章: ASP.NET: clear user control output cache

原创粉丝点击