CacheSection Clase

Definición

Configura las opciones de caché global para una aplicación de ASP.NET. Esta clase no puede heredarse.

public ref class CacheSection sealed : System::Configuration::ConfigurationSection
public sealed class CacheSection : System.Configuration.ConfigurationSection
type CacheSection = class
    inherit ConfigurationSection
Public NotInheritable Class CacheSection
Inherits ConfigurationSection
Herencia

Ejemplos

En el ejemplo de código siguiente se muestra una página y el archivo de código relacionado que se usa para acceder a los atributos de CacheSection sección.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ReadWriteCache.aspx.cs" Inherits="ReadWriteCache" %>

<!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 runat="server">
    <title>Read Write Application Cache</title>
</head>
<body>
    <form id="form1" runat="server">
        <h2>Read Write Application Cache</h2>

        <asp:Label ID="Label1" Text="[Application Cache goes here.]" runat="server"></asp:Label>
        
        <hr />

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Write Cache" />    
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Read Cache" />
    </form>
</body>
</html>
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="ReadWriteCache.aspx.vb" Inherits="ReadWriteCache" %>

<!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>Read Write Application Cache</title>
</head>
<body>
    <form id="form1" runat="server">
        <h2>Read Write Application Cache</h2>

        <asp:Label ID="Label1" Text="[Application Cache goes here.]" runat="server"></asp:Label>
        
        <hr />

        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Write Cache" />    
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Read Cache" />
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ReadWriteCache : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            Label1.Text = "Application Cache goes here.";
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        // Get the application configuration file.
        System.Configuration.Configuration config =
          System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/");

        System.Web.Configuration.CacheSection cacheSection =
            (System.Web.Configuration.CacheSection)config.GetSection(
                "system.web/caching/cache");

        // Increase the PrivateBytesLimit property to 0.
        cacheSection.PrivateBytesLimit = 
            cacheSection.PrivateBytesLimit + 10;

        // Increase memory limit.
        cacheSection.PercentagePhysicalMemoryUsedLimit = 
            cacheSection.PercentagePhysicalMemoryUsedLimit + 1;

        // Increase poll time.
        cacheSection.PrivateBytesPollTime =
            cacheSection.PrivateBytesPollTime + TimeSpan.FromMinutes(1);

        // Enable or disable memory collection.
        cacheSection.DisableMemoryCollection = 
                !cacheSection.DisableMemoryCollection;

        // Enable or disable cache expiration.
        cacheSection.DisableExpiration =
            !cacheSection.DisableExpiration;

        // Save the configuration file.
        config.Save(System.Configuration.ConfigurationSaveMode.Modified);      
    }

    protected void Button2_Click(object sender, EventArgs e)
    {

        // Get the application configuration file.
        System.Configuration.Configuration config =
          System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/");

        System.Web.Configuration.CacheSection cacheSection =
            (System.Web.Configuration.CacheSection)config.GetSection(
                "system.web/caching/cache");

        // Read the cache section.
        System.Text.StringBuilder buffer = new System.Text.StringBuilder();

        string currentFile = cacheSection.CurrentConfiguration.FilePath;
        bool dExpiration = cacheSection.DisableExpiration;
        bool dMemCollection = cacheSection.DisableMemoryCollection;
        TimeSpan pollTime = cacheSection.PrivateBytesPollTime;
        int phMemUse = cacheSection.PercentagePhysicalMemoryUsedLimit;
        long pvBytesLimit = cacheSection.PrivateBytesLimit;

        string cacheEntry = String.Format("File: {0} <br/>", currentFile);
        buffer.Append(cacheEntry);
        cacheEntry = String.Format("Expiration Disabled: {0} <br/>", dExpiration);
        buffer.Append(cacheEntry);
        cacheEntry = String.Format("Memory Collection Disabled: {0} <br/>", dMemCollection);
        buffer.Append(cacheEntry);
        cacheEntry = String.Format("Poll Time: {0} <br/>", pollTime.ToString());
        buffer.Append(cacheEntry);
        cacheEntry = String.Format("Memory Limit: {0} <br/>", phMemUse.ToString());
        buffer.Append(cacheEntry);
        cacheEntry = String.Format("Bytes Limit: {0} <br/>", pvBytesLimit.ToString());
        buffer.Append(cacheEntry);

        Label1.Text = buffer.ToString();
    }
}
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Public Class ReadWriteCache
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If Not IsPostBack Then
            Label1.Text = "Application Cache goes here."
        End If

    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' Get the application configuration file.
        Dim config As System.Configuration.Configuration =
            System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/")


        Dim cacheSection As System.Web.Configuration.CacheSection =
            CType(config.GetSection("system.web/caching/cache"), System.Web.Configuration.CacheSection)

        ' Increase the PrivateBytesLimit property to 0.
        cacheSection.PrivateBytesLimit = cacheSection.PrivateBytesLimit + 10


        ' Increase memory limit.
        cacheSection.PercentagePhysicalMemoryUsedLimit =
            cacheSection.PercentagePhysicalMemoryUsedLimit + 1

        ' Increase poll time.
        cacheSection.PrivateBytesPollTime =
            cacheSection.PrivateBytesPollTime + TimeSpan.FromMinutes(1)


        ' Enable or disable memory collection.
        cacheSection.DisableMemoryCollection =
            Not cacheSection.DisableMemoryCollection

        ' Enable or disable cache expiration.
        cacheSection.DisableExpiration =
            Not cacheSection.DisableExpiration

        ' Save the configuration file.
        config.Save(System.Configuration.ConfigurationSaveMode.Modified)

    End Sub

    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)

        ' Get the application configuration file.
        Dim config As System.Configuration.Configuration =
            System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/")


        Dim cacheSection As System.Web.Configuration.CacheSection =
            CType(config.GetSection("system.web/caching/cache"), System.Web.Configuration.CacheSection)

        ' Read the cache section.
        Dim buffer As New System.Text.StringBuilder()

        Dim currentFile As String = cacheSection.CurrentConfiguration.FilePath
        Dim dExpiration As Boolean = cacheSection.DisableExpiration
        Dim dMemCollection As Boolean = cacheSection.DisableMemoryCollection
        Dim pollTime As TimeSpan = cacheSection.PrivateBytesPollTime
        Dim phMemUse As Integer = cacheSection.PercentagePhysicalMemoryUsedLimit
        Dim pvBytesLimit As Long = cacheSection.PrivateBytesLimit

        Dim cacheEntry As String = String.Format("File: {0} <br/>", currentFile)
        buffer.Append(cacheEntry)
        cacheEntry = String.Format("Expiration Disabled: {0} <br/>", dExpiration)
        buffer.Append(cacheEntry)
        cacheEntry = String.Format("Memory Collection Disabled: {0} <br/>", dMemCollection)
        buffer.Append(cacheEntry)
        cacheEntry = String.Format("Poll Time: {0} <br/>", pollTime.ToString())
        buffer.Append(cacheEntry)
        cacheEntry = String.Format("Memory Limit: {0} <br/>", phMemUse.ToString())
        buffer.Append(cacheEntry)
        cacheEntry = String.Format("Bytes Limit: {0} <br/>", pvBytesLimit.ToString())
        buffer.Append(cacheEntry)

        Label1.Text = buffer.ToString()
    End Sub
End Class

Comentarios

La CacheSection clase proporciona una manera de obtener acceso mediante programación y modificar la <cache> sección de un archivo de configuración.

La característica de almacenamiento en caché de ASP.NET se implementa mediante la clase Cache. Para obtener más información, consulte Almacenamiento en caché.

Note

CacheSection puede escribir información en la sección relacionada del archivo de configuración según las restricciones definidas por la propiedad AllowDefinition section cuyo valor es MachineToApplication. Cualquier intento de escribir en un archivo de configuración en un nivel no permitido en la jerarquía producirá un mensaje de error generado por el analizador. Sin embargo, puede usar esta clase para leer información de configuración en cualquier nivel de la jerarquía.

Una caché es una tabla hash específica de la aplicación que se usa para almacenar datos a los que se accede con frecuencia. El estado de la aplicación y la sesión son similares a la memoria caché, el estado de la aplicación es el más similar, debido a su ámbito de toda la aplicación. Una de las mayores diferencias entre la memoria caché y el mecanismo de estado de la aplicación es que la memoria caché admite dependencias Estas dependencias permiten crear aplicaciones que quitan automáticamente los elementos almacenados en caché cuando se producen determinados eventos.

Constructores

Nombre Description
CacheSection()

Inicializa una nueva instancia de la clase CacheSection.

Propiedades

Nombre Description
CurrentConfiguration

Obtiene una referencia a la instancia de nivel Configuration superior que representa la jerarquía de configuración a la que pertenece la instancia actual ConfigurationElement .

(Heredado de ConfigurationElement)
DefaultProvider

Obtiene o establece el proveedor predeterminado.

DisableExpiration

Obtiene o establece un valor que indica si la expiración de la memoria caché está deshabilitada.

DisableMemoryCollection

Obtiene o establece un valor que indica si la colección de memoria caché está deshabilitada.

ElementInformation

Obtiene un ElementInformation objeto que contiene la información y la funcionalidad no personalizables del ConfigurationElement objeto .

(Heredado de ConfigurationElement)
ElementProperty

Obtiene el ConfigurationElementProperty objeto que representa el ConfigurationElement propio objeto.

(Heredado de ConfigurationElement)
EvaluationContext

Obtiene el objeto ContextInformation para el objeto ConfigurationElement.

(Heredado de ConfigurationElement)
HasContext

Obtiene un valor que indica si la CurrentConfiguration propiedad es null.

(Heredado de ConfigurationElement)
Item[ConfigurationProperty]

Obtiene o establece una propiedad o atributo de este elemento de configuración.

(Heredado de ConfigurationElement)
Item[String]

Obtiene o establece una propiedad, un atributo o un elemento secundario de este elemento de configuración.

(Heredado de ConfigurationElement)
LockAllAttributesExcept

Obtiene la colección de atributos bloqueados.

(Heredado de ConfigurationElement)
LockAllElementsExcept

Obtiene la colección de elementos bloqueados.

(Heredado de ConfigurationElement)
LockAttributes

Obtiene la colección de atributos bloqueados.

(Heredado de ConfigurationElement)
LockElements

Obtiene la colección de elementos bloqueados.

(Heredado de ConfigurationElement)
LockItem

Obtiene o establece un valor que indica si el elemento está bloqueado.

(Heredado de ConfigurationElement)
PercentagePhysicalMemoryUsedLimit

Obtiene o establece un valor que indica el porcentaje máximo de uso de memoria virtual.

PrivateBytesLimit

Obtiene o establece un valor que indica el tamaño máximo del espacio privado del proceso de trabajo.

PrivateBytesPollTime

Obtiene o establece un valor que indica el intervalo de tiempo entre el sondeo para el uso de memoria del proceso de trabajo.

Properties

Obtiene la colección de propiedades.

(Heredado de ConfigurationElement)
Providers

Obtiene la colección de configuración del proveedor.

SectionInformation

Obtiene un SectionInformation objeto que contiene la información y la funcionalidad no personalizables del ConfigurationSection objeto .

(Heredado de ConfigurationSection)

Métodos

Nombre Description
DeserializeElement(XmlReader, Boolean)

Lee XML del archivo de configuración.

(Heredado de ConfigurationElement)
DeserializeSection(XmlReader)

Lee XML del archivo de configuración.

(Heredado de ConfigurationSection)
Equals(Object)

Compara la instancia actual ConfigurationElement con el objeto especificado.

(Heredado de ConfigurationElement)
GetHashCode()

Obtiene un valor único que representa la instancia actual ConfigurationElement .

(Heredado de ConfigurationElement)
GetRuntimeObject()

Devuelve un objeto personalizado cuando se invalida en una clase derivada.

(Heredado de ConfigurationSection)
GetTransformedAssemblyString(String)

Devuelve la versión transformada del nombre de ensamblado especificado.

(Heredado de ConfigurationElement)
GetTransformedTypeString(String)

Devuelve la versión transformada del nombre de tipo especificado.

(Heredado de ConfigurationElement)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
Init()

Establece el ConfigurationElement objeto en su estado inicial.

(Heredado de ConfigurationElement)
InitializeDefault()

Se usa para inicializar un conjunto predeterminado de valores para el ConfigurationElement objeto .

(Heredado de ConfigurationElement)
IsModified()

Indica si este elemento de configuración se ha modificado desde que se guardó o cargó por última vez cuando se implementó en una clase derivada.

(Heredado de ConfigurationSection)
IsReadOnly()

Obtiene un valor que indica si el ConfigurationElement objeto es de solo lectura.

(Heredado de ConfigurationElement)
ListErrors(IList)

Agrega los errores de propiedad no válida en este ConfigurationElement objeto y, en todos los subelementos, a la lista pasada.

(Heredado de ConfigurationElement)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
OnDeserializeUnrecognizedAttribute(String, String)

Obtiene un valor que indica si se encuentra un atributo desconocido durante la deserialización.

(Heredado de ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Obtiene un valor que indica si se encuentra un elemento desconocido durante la deserialización.

(Heredado de ConfigurationElement)
OnRequiredPropertyNotFound(String)

Produce una excepción cuando no se encuentra una propiedad necesaria.

(Heredado de ConfigurationElement)
PostDeserialize()

Se llama después de la deserialización.

(Heredado de ConfigurationElement)
PreSerialize(XmlWriter)

Se llama antes de la serialización.

(Heredado de ConfigurationElement)
Reset(ConfigurationElement)

Restablece el estado interno del ConfigurationElement objeto, incluidos los bloqueos y las colecciones de propiedades.

(Heredado de ConfigurationElement)
ResetModified()

Restablece el valor del IsModified() método a false cuando se implementa en una clase derivada.

(Heredado de ConfigurationSection)
SerializeElement(XmlWriter, Boolean)

Escribe el contenido de este elemento de configuración en el archivo de configuración cuando se implementa en una clase derivada.

(Heredado de ConfigurationElement)
SerializeSection(ConfigurationElement, String, ConfigurationSaveMode)

Crea una cadena XML que contiene una vista no combinada del ConfigurationSection objeto como una sola sección para escribir en un archivo.

(Heredado de ConfigurationSection)
SerializeToXmlElement(XmlWriter, String)

Escribe las etiquetas externas de este elemento de configuración en el archivo de configuración cuando se implementa en una clase derivada.

(Heredado de ConfigurationElement)
SetPropertyValue(ConfigurationProperty, Object, Boolean)

Establece una propiedad en el valor especificado.

(Heredado de ConfigurationElement)
SetReadOnly()

Establece la IsReadOnly() propiedad para el ConfigurationElement objeto y todos los subelementos.

(Heredado de ConfigurationElement)
ShouldSerializeElementInTargetVersion(ConfigurationElement, String, FrameworkName)

Indica si el elemento especificado se debe serializar cuando la jerarquía de objetos de configuración se serializa para la versión de destino especificada de .NET Framework.

(Heredado de ConfigurationSection)
ShouldSerializePropertyInTargetVersion(ConfigurationProperty, String, FrameworkName, ConfigurationElement)

Indica si la propiedad especificada se debe serializar cuando la jerarquía de objetos de configuración se serializa para la versión de destino especificada de .NET Framework.

(Heredado de ConfigurationSection)
ShouldSerializeSectionInTargetVersion(FrameworkName)

Indica si se debe serializar la instancia de ConfigurationSection actual cuando la jerarquía de objetos de configuración se serializa para la versión de destino especificada de .NET Framework.

(Heredado de ConfigurationSection)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)
Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode)

Modifica el ConfigurationElement objeto para quitar todos los valores que no se deben guardar.

(Heredado de ConfigurationElement)

Se aplica a

Consulte también