ControlCachePolicy 类

定义

提供对 ASP.NET 用户控件的输出缓存设置的编程访问。Provides programmatic access to an ASP.NET user control's output cache settings.

public ref class ControlCachePolicy sealed
public sealed class ControlCachePolicy
type ControlCachePolicy = class
Public NotInheritable Class ControlCachePolicy
继承
ControlCachePolicy

示例

下面的代码示例演示如何在运行时动态加载用户控件并以编程方式进行操作。The following code example demonstrates how a user control can be loaded dynamically and manipulated programmatically at run time. PartialCachingAttribute 属性应用于名为 SimpleControl的用户控件,这意味着在运行时由 PartialCachingControl 控件包装用户控件。The PartialCachingAttribute attribute is applied to a user control named SimpleControl, which means the user control is wrapped by a PartialCachingControl control at run time. SimpleControl 对象的缓存设置可以通过其关联的 ControlCachePolicy 对象以编程方式进行操作,该对象可通过对包装该对象的 PartialCachingControl 控件的引用提供。The SimpleControl object's caching settings can be programmatically manipulated through its associated ControlCachePolicy object, which is available through a reference to the PartialCachingControl control that wraps it. 在此示例中,如果满足某些条件,则在页初始化期间检查 Duration 属性,并使用 SetSlidingExpirationSetExpires 方法进行更改。In this example, the Duration property is examined during page initialization and changed using the SetSlidingExpiration and SetExpires methods if some conditions are met.

<%@ Page Language="C#" %>
<%@ Reference Control="SimpleControl.ascx" %>
<script language="C#" runat="server">

// The following example demonstrates how to load a user control dynamically at run time, and
// work with the ControlCachePolicy object associated with it.

// Loads and displays a UserControl defined in a seperate Logonform.ascx file.
// You need to have "SimpleControl.ascx" file in 
// the same directory as the aspx file. 

void Page_Init(object sender, System.EventArgs e) {
    
    // Obtain a PartialCachingControl object which wraps the 'LogOnControl' user control.
    PartialCachingControl pcc = LoadControl("SimpleControl.ascx") as PartialCachingControl;        
    
    // If the control is slated to expire in greater than 60 Seconds
    if (pcc.CachePolicy.Duration > TimeSpan.FromSeconds(60) ) 
    {        
        // Make it expire faster. Set a new expiration time to 30 seconds, and make it
        // an absolute expiration if it isnt already.        
        pcc.CachePolicy.SetExpires(DateTime.Now.Add(TimeSpan.FromSeconds(30)));
        pcc.CachePolicy.SetSlidingExpiration(false);
    }                    
    Controls.Add(pcc);
}
</script>
<%@ Page Language="VB" %>
<%@ Reference Control="SimpleControl.ascx" %>
<script language="VB" runat="server">

    ' The following example demonstrates how to load a user control dynamically at run time, and
    ' work with the ControlCachePolicy object associated with it.

    ' Loads and displays a UserControl defined in a seperate Logonform.ascx file.
    ' You need to have "SimpleControl.ascx" file in 
    ' the same directory as the aspx file. 

    Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs)
    
        ' Obtain a PartialCachingControl object which wraps the 'LogOnControl' user control.
        Dim pcc As PartialCachingControl
        pcc = LoadControl("SimpleControl.ascx")
    
        ' If the control is slated to expire in greater than 60 Seconds
        If (pcc.CachePolicy.Duration > TimeSpan.FromSeconds(60)) Then
            ' Make it expire faster. Set a new expiration time to 30 seconds, and make it
            ' an absolute expiration if it isnt already.        
            pcc.CachePolicy.SetExpires(DateTime.Now.Add(TimeSpan.FromSeconds(30)))
            pcc.CachePolicy.SetSlidingExpiration(False)
        End If
        Controls.Add(pcc)
    End Sub
</script>

下面的代码示例演示如何使用 Web 窗体页中的 SimpleControl 用户控件。The following code example demonstrates using the SimpleControl user control from a Web Forms page. 若要成功运行此示例,请确保用户控件文件(.ascx)、其代码隐藏文件(.cs 或 .vb)以及承载用户控件(.aspx)的 Web 窗体页位于同一个目录中。To run this example successfully, make sure the user control file (.ascx), its code-behind file (.cs or .vb), and the Web Forms page that hosts the user control (.aspx) are in the same directory.

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

[PartialCaching(100)]
public partial class SimpleControl : System.Web.UI.UserControl
{    
    protected void Page_Load(object sender, EventArgs e)
    {
        ItemsRemaining.Text = GetAvailableItems().ToString();
        CacheTime.Text = DateTime.Now.ToLongTimeString();
    }

    private int GetAvailableItems()
    {
        SqlConnection sqlConnection = new SqlConnection
            ("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;");
        SqlCommand sqlCommand = sqlConnection.CreateCommand();
        sqlCommand.CommandType = CommandType.StoredProcedure;
        sqlCommand.CommandText = "GetRemainingItems";
        sqlConnection.Open();
        int items = (int)sqlCommand.ExecuteScalar();
        sqlConnection.Close();
        return items;
    }
}
Imports System.Data.SqlClient

Partial Class SimpleControl
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        ItemsRemaining.Text = GetAvailableItems().ToString()
        CacheTime.Text = DateTime.Now.ToLongTimeString()
    End Sub

    Private Function GetAvailableItems() As Integer
        Dim sqlConnection As SqlConnection
        Dim sqlCommand As SqlCommand
        Dim items As Integer

        sqlConnection = New SqlConnection("Initial Catalog=Northwind;Data Source=localhost;Integrated Security=SSPI;")
        sqlCommand = sqlConnection.CreateCommand()
        sqlCommand.CommandType = Data.CommandType.StoredProcedure
        sqlCommand.CommandText = "GetRemainingItems"
        sqlConnection.Open()
        items = CInt(sqlCommand.ExecuteScalar())
        sqlConnection.Close()
        Return items
    End Function
End Class
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SimpleControl.ascx.cs" Inherits="SimpleControl" %>
<!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">
<head id="Head1" runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
<form id="Form1" runat="server">
<table cellspacing="15">
<tr>
<td><b>Available items: </b></td>
<td>
    <asp:Label ID="ItemsRemaining" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td><b>As of: </b></td>
<td>
    <asp:Label ID="CacheTime" runat="server" Text="Label"></asp:Label>
</td>
</tr>
</table>
</form>
</body>
</html>
<%@ Control Language="VB" AutoEventWireup="true" CodeFile="SimpleControl.ascx.vb" Inherits="SimpleControl" %>
<!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">
<head id="Head1" runat="server">
    <title>ASP.NET Example</title>
</head>
<body>
<form id="Form1" runat="server">
<table cellspacing="15">
<tr>
<td><b>Available items: </b></td>
<td>
    <asp:Label ID="ItemsRemaining" runat="server" Text="Label"></asp:Label>
</td>
</tr>
<tr>
<td><b>As of: </b></td>
<td>
    <asp:Label ID="CacheTime" runat="server" Text="Label"></asp:Label>
</td>
</tr>
</table>
</form>
</body>
</html>

注解

编程用户控件方案中的开发人员使用 ControlCachePolicy 类来指定用户控件(.ascx 文件)的输出缓存设置。The ControlCachePolicy class is used by developers in programmatic user control scenarios to specify output caching settings for user controls (.ascx files). ASP.NET 在 BasePartialCachingControl 实例中嵌入用户控件。ASP.NET embeds user controls within a BasePartialCachingControl instance. BasePartialCachingControl 类表示启用了输出缓存的用户控件。The BasePartialCachingControl class represents a user control that has output caching enabled. 当访问 PartialCachingControl 控件的 BasePartialCachingControl.CachePolicy 属性时,将始终接收有效的 ControlCachePolicy 对象。When you access the BasePartialCachingControl.CachePolicy property of a PartialCachingControl control, you will always receive a valid ControlCachePolicy object. 但是,如果您访问 UserControl 控件的 UserControl.CachePolicy 属性,则只有在用户控件已被 BasePartialCachingControl 控件包装的情况下,才会收到有效的 ControlCachePolicy 对象。However, if you access the UserControl.CachePolicy property of a UserControl control, you receive a valid ControlCachePolicy object only if the user control is already wrapped by a BasePartialCachingControl control. 如果未包装,则当你尝试对属性返回的 ControlCachePolicy 对象没有关联的 BasePartialCachingControl时,将引发异常。If it is not wrapped, the ControlCachePolicy object returned by the property will throw exceptions when you attempt to manipulate it because it does not have an associated BasePartialCachingControl. 若要确定 UserControl 实例是否支持缓存而不生成异常,请检查 SupportsCaching 属性。To determine whether a UserControl instance supports caching without generating exceptions, inspect the SupportsCaching property.

使用 ControlCachePolicy 类是可以实现输出缓存的多种方式之一。Using the ControlCachePolicy class is one of several ways you can enable output caching. 以下列表描述了可用于启用输出缓存的方法:The following list describes methods you can use to enable output caching:

  • 使用指令启用声明性方案中的输出缓存。Use the directive to enable output caching in declarative scenarios.

  • 使用 PartialCachingAttribute 特性可为代码隐藏文件中的用户控件启用缓存。Use the PartialCachingAttribute attribute to enable caching for a user control in a code-behind file.

  • 使用 ControlCachePolicy 类在编程方案中指定缓存设置,在此方案中,使用以前的方法之一并使用 TemplateControl.LoadControl 方法动态加载已启用缓存的 BasePartialCachingControl 实例。Use the ControlCachePolicy class to specify cache settings in programmatic scenarios in which you are working with BasePartialCachingControl instances that have been cache-enabled using one of the previous methods and dynamically loaded using the TemplateControl.LoadControl method. 只能在控件生命周期的 InitPreRender 阶段之间成功地处理 ControlCachePolicy 实例。A ControlCachePolicy instance can be successfully manipulated only between the Init and PreRender stages of the control life cycle. 如果在 PreRender 阶段之后修改 ControlCachePolicy 对象,ASP.NET 将引发异常,因为呈现控件后所做的任何更改都不会影响缓存设置(控件在 Render 阶段缓存)。If you modify a ControlCachePolicy object after the PreRender phase, ASP.NET throws an exception, because any changes made after the control is rendered cannot actually affect cache settings (a control is cached during the Render stage). 最后,用户控件实例(因此它的 ControlCachePolicy 对象)仅适用于实际呈现时的编程操作。Finally, a user control instance (and therefore its ControlCachePolicy object) is only available for programmatic manipulation when it is actually rendered.

属性

Cached

获取或设置一个值,该值指示是否为用户控件启用片段缓存。Gets or sets a value indicating whether fragment caching is enabled for the user control.

Dependency

获取或设置与缓存的用户控件输出关联的 CacheDependency 类的实例。Gets or sets an instance of the CacheDependency class associated with the cached user control output.

Duration

获取或设置缓存的项将在输出缓存中保留的时间。Gets or sets the amount of time that cached items are to remain in the output cache.

ProviderName

获取或设置与控件实例关联的输出缓存提供程序的名称,。Gets or sets the name of the output-cache provider that is associated with a control instance.

SupportsCaching

获取一个值,该值指示用户控件是否支持缓存。Gets a value indicating whether the user control supports caching.

VaryByControl

获取或设置要用来改变缓存输出的控件标识符列表。Gets or sets a list of control identifiers to vary the cached output by.

VaryByParams

获取或设置要用来改变缓存输出的 GETPOST 参数名称列表。Gets or sets a list of GET or POST parameter names to vary the cached output by.

方法

Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
SetExpires(DateTime)

指示包装用户控件的 BasePartialCachingControl 控件在指定的日期和时间使缓存项过期。Instructs the BasePartialCachingControl control that wraps the user control to expire the cache entry at the specified date and time.

SetSlidingExpiration(Boolean)

指示包装用户控件的 BasePartialCachingControl 控件将用户控件的缓存项设置为使用可调或绝对过期。Instructs the BasePartialCachingControl control that wraps the user control to set the user control's cache entry to use sliding or absolute expiration.

SetVaryByCustom(String)

设置要由输出缓存用来改变用户控件的自定义字符串列表。Sets a list of custom strings that the output cache will use to vary the user control.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

适用于

另请参阅