CacheSection Classe

Definição

Define as configurações de cache global para um aplicativo ASP.NET. Essa classe não pode ser herdada.

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
Herança

Exemplos

O exemplo de código a seguir mostra uma página e o arquivo de código relacionado usado para acessar os atributos de CacheSection seção.

<%@ 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

Comentários

A classe CacheSection oferece uma maneira de acessar e modificar programaticamente a seção <cache> de um arquivo de configuração.

O recurso de cache ASP.NET é implementado pela Cache classe. Para obter mais informações, consulte Caching.

Observação

As CacheSection informações podem ser gravadas na seção relacionada do arquivo de configuração de acordo com as restrições definidas pela propriedade AllowDefinition de seção cujo valor é MachineToApplication. Qualquer tentativa de gravar em um arquivo de configuração em um nível não permitido na hierarquia resultará em uma mensagem de erro gerada pelo analisador. No entanto, você pode usar essa classe para ler informações de configuração em qualquer nível na hierarquia.

Um cache é uma tabela de hash específica do aplicativo usada para armazenar dados acessados com frequência. O estado do aplicativo e da sessão são semelhantes ao cache, sendo o estado do aplicativo o mais semelhante devido ao escopo de todo o aplicativo. Uma das maiores diferenças entre o cache e o mecanismo de estado do aplicativo é que o cache dá suporte a dependências Essas dependências possibilitam a criação de aplicativos que removem automaticamente itens armazenados em cache quando determinados eventos ocorrem.

Construtores

CacheSection()

Inicializa uma nova instância da classe CacheSection.

Propriedades

CurrentConfiguration

Obtém uma referência para a instância Configuration de nível superior que representa a hierarquia de configuração à qual a instância atual ConfigurationElement pertence.

(Herdado de ConfigurationElement)
DefaultProvider

Obtém ou define o provedor padrão.

DisableExpiration

Obtém ou define um valor que indica se a expiração do cache está desabilitada.

DisableMemoryCollection

Obtém ou define um valor que indica se a coleta de memória cache está desabilitada.

ElementInformation

Obtém um objeto ElementInformation que contém as informações não personalizáveis e a funcionalidade do objeto ConfigurationElement.

(Herdado de ConfigurationElement)
ElementProperty

Obtém o objeto ConfigurationElementProperty que representa o próprio objeto ConfigurationElement.

(Herdado de ConfigurationElement)
EvaluationContext

Obtém o objeto ContextInformation para o objeto ConfigurationElement.

(Herdado de ConfigurationElement)
HasContext

Obtém um valor que indica se a propriedade CurrentConfiguration é null.

(Herdado de ConfigurationElement)
Item[ConfigurationProperty]

Obtém ou define uma propriedade ou um atributo desse elemento de configuração.

(Herdado de ConfigurationElement)
Item[String]

Obtém ou define uma propriedade, atributo ou elemento filho desse elemento de configuração.

(Herdado de ConfigurationElement)
LockAllAttributesExcept

Obtém a coleção de atributos bloqueados.

(Herdado de ConfigurationElement)
LockAllElementsExcept

Obtém a coleção de elementos bloqueados.

(Herdado de ConfigurationElement)
LockAttributes

Obtém a coleção de atributos bloqueados.

(Herdado de ConfigurationElement)
LockElements

Obtém a coleção de elementos bloqueados.

(Herdado de ConfigurationElement)
LockItem

Obtém ou define um valor que indica se o elemento está bloqueado.

(Herdado de ConfigurationElement)
PercentagePhysicalMemoryUsedLimit

Obtém ou define um valor que indica o percentual máximo de uso de memória virtual.

PrivateBytesLimit

Obtém ou define um valor que indica o tamanho máximo do espaço privado de processo de trabalho.

PrivateBytesPollTime

Obtém ou define um valor que indica o intervalo de tempo entre as sondagens de uso de memória do processo de trabalho.

Properties

Obtém a coleção de propriedades.

(Herdado de ConfigurationElement)
Providers

Obtém o conjunto de configurações do provedor.

SectionInformation

Obtém um objeto SectionInformation que contém as informações não personalizáveis e a funcionalidade do objeto ConfigurationSection.

(Herdado de ConfigurationSection)

Métodos

DeserializeElement(XmlReader, Boolean)

Lê o XML do arquivo de configuração.

(Herdado de ConfigurationElement)
DeserializeSection(XmlReader)

Lê o XML do arquivo de configuração.

(Herdado de ConfigurationSection)
Equals(Object)

Compara a instância ConfigurationElement atual com o objeto especificado.

(Herdado de ConfigurationElement)
GetHashCode()

Obtém um valor exclusivo que representa a instância ConfigurationElement atual.

(Herdado de ConfigurationElement)
GetRuntimeObject()

Retorna um objeto personalizado quando substituído em uma classe derivada.

(Herdado de ConfigurationSection)
GetTransformedAssemblyString(String)

Retorna a versão transformada do nome do assembly especificado.

(Herdado de ConfigurationElement)
GetTransformedTypeString(String)

Retorna a versão transformada do nome do tipo especificado.

(Herdado de ConfigurationElement)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
Init()

Define o objeto ConfigurationElement para seu estado inicial.

(Herdado de ConfigurationElement)
InitializeDefault()

Usado para inicializar um conjunto padrão de valores para o objeto ConfigurationElement.

(Herdado de ConfigurationElement)
IsModified()

Indica se este elemento de configuração foi modificado desde a última vez em que foi salvo ou carregado quando implementado em uma classe derivada.

(Herdado de ConfigurationSection)
IsReadOnly()

Obtém um valor que indica se o objeto ConfigurationElement é somente leitura.

(Herdado de ConfigurationElement)
ListErrors(IList)

Adiciona os erros de propriedade inválida deste objeto ConfigurationElement e de todos os subelementos à lista passada.

(Herdado de ConfigurationElement)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
OnDeserializeUnrecognizedAttribute(String, String)

Obtém um valor que indica se um atributo desconhecido é encontrado durante a desserialização.

(Herdado de ConfigurationElement)
OnDeserializeUnrecognizedElement(String, XmlReader)

Obtém um valor que indica se um elemento desconhecido é encontrado durante a desserialização.

(Herdado de ConfigurationElement)
OnRequiredPropertyNotFound(String)

Gera uma exceção quando uma propriedade necessária não é encontrada.

(Herdado de ConfigurationElement)
PostDeserialize()

Chamado depois da desserialização.

(Herdado de ConfigurationElement)
PreSerialize(XmlWriter)

Chamado antes da serialização.

(Herdado de ConfigurationElement)
Reset(ConfigurationElement)

Redefine o estado interno do objeto ConfigurationElement, incluindo os bloqueios e as coleções de propriedades.

(Herdado de ConfigurationElement)
ResetModified()

Redefine o valor do método IsModified() para false quando implementado em uma classe derivada.

(Herdado de ConfigurationSection)
SerializeElement(XmlWriter, Boolean)

Grava o conteúdo desse elemento de configuração no arquivo de configuração quando implementado em uma classe derivada.

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

Cria uma cadeia de caracteres XML que contém uma exibição não mesclada do objeto ConfigurationSection como uma única seção a ser gravada em um arquivo.

(Herdado de ConfigurationSection)
SerializeToXmlElement(XmlWriter, String)

Grava as marcas externas desse elemento de configuração no arquivo de configuração quando implementado em uma classe derivada.

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

Define uma propriedade para o valor especificado.

(Herdado de ConfigurationElement)
SetReadOnly()

Define a propriedade IsReadOnly() para o objeto ConfigurationElement e para todos os subelementos.

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

Indica se o elemento especificado deve ser serializado quando a hierarquia de objeto de configuração é serializada para a versão de destino especificada do .NET Framework.

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

Indica se a propriedade especificada deve ser serializada quando a hierarquia de objetos de configuração é serializada para a versão de destino especificada do .NET Framework.

(Herdado de ConfigurationSection)
ShouldSerializeSectionInTargetVersion(FrameworkName)

Indica se a instância atual ConfigurationSection deve ser serializada quando a hierarquia de objetos de configuração é serializada para a versão de destino especificada do .NET Framework.

(Herdado de ConfigurationSection)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

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

Modifica o objeto ConfigurationElement para remover todos os valores que não devem ser salvos.

(Herdado de ConfigurationElement)

Aplica-se a

Confira também