HttpResponse.AddCacheItemDependency(String) 方法

定义

使缓存响应的有效性依赖于缓存中的其他项。

public void AddCacheItemDependency(string cacheKey);

参数

cacheKey
String

缓存的响应所依赖的项的键。

示例

以下示例是缓存输出 ASP.NET 用户控件。 控件的代码使用作为其参数传递的对象中Cache存储的项的键调用 AddCacheItemDependency 方法。 如果缓存中不存在该项,则存储在输出缓存中的控件响应将失效。 这意味着,在后续请求中,控件响应的新版本将添加到输出缓存中。

接下来,代码检查与键关联的 bookData 项是否存储在 对象中 Cache ,并显示依赖于结果的两行文本中的一行。 然后,代码通过调用自定义类的DataGrid共享GetBookData方法设置DataSource名为 dgBooks的 控件的 属性,并使用 方法填充 DataGridDataBindDataHelper

    <%@ Control Language="c#" %>
    <%@ Outputcache duration="10" varybyparam="none" shared="True" %>
    <%@ Import Namespace = "Samples.AspNet.CS" %>
    <%@ Import Namespace = "System.Data" %>

<script runat="server">

    private void Page_Load(object sender, System.EventArgs e)
    {
    
        // Make user control invalid if the
        // cache item changes or expires.
        Response.AddCacheItemDependency("bookData");

        // Create a DataView object.
        DataView source = (DataView)Cache["bookData"];
    
        // Check if the view is stored in the cache
        // and generate the right label text
        // dependent upon what is returned.
        if (source == null)
        {
            source = DataHelper.GetBookData();
            lblCacheMsg.Text = "Data generated explicitly.";
        }
        else
        {
            lblCacheMsg.Text = "Data retrieved from application cache.";
        }
    
        dgBooks.DataSource = source;
        dgBooks.DataBind();
    
        lblOutputMessage.Text = DateTime.Now.ToString();
    }

</script>
    <table>
        <tbody>
            <tr>
                <th>
                    Books</th>
                <td>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:DataGrid id="dgBooks" runat="server"></asp:DataGrid>
                </td>
                <td>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label id="lblCacheMsg" runat="server"></asp:Label>
                </td>
                <td>
                </td>
            </tr>
            <tr>
                <td>
                    The control was created at: 
                </td>
                <td>
                    <asp:Label id="lblOutputMessage" runat="server"></asp:Label>
                </td>
            </tr>
        </tbody>
    </table>

注解

从缓存中删除与 cacheKey 参数对应的项时,当前项的缓存响应无效。

适用于

产品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1

另请参阅