CacheSection Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Configura as definições globais de cache para uma aplicação ASP.NET. Esta 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 seguinte mostra uma página e o ficheiro de código relacionado usado para aceder aos CacheSection atributos da secçã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
Observações
A CacheSection classe fornece uma forma de aceder e modificar programaticamente a <cache> secção de um ficheiro de configuração.
A funcionalidade de cache ASP.NET é implementada pela classe Cache. Para mais informações, consulte Caching.
Note
Podem CacheSection escrever informação na secção relacionada do ficheiro de configuração de acordo com as restrições definidas pela propriedade AllowDefinition de secção cujo valor é MachineToApplication. Qualquer tentativa de escrever num ficheiro de configuração a um nível não permitido na hierarquia resultará numa mensagem de erro gerada pelo parser. No entanto, pode usar esta classe para ler informação de configuração em qualquer nível da hierarquia.
Uma cache é uma tabela de hash específica de uma aplicação usada para armazenar dados frequentemente acedidos. O estado da aplicação e da sessão são semelhantes à cache, sendo o estado da aplicação o mais semelhante, devido ao seu âmbito aplical. Uma das maiores diferenças entre a cache e o mecanismo de estado da aplicação é que a cache suporta dependências. Estas dependências permitem construir aplicações que removem automaticamente itens em cache quando certos eventos ocorrem.
Construtores
| Name | Description |
|---|---|
| CacheSection() |
Inicializa uma nova instância da CacheSection classe. |
Propriedades
| Name | Description |
|---|---|
| CurrentConfiguration |
Obtém uma referência à instância de topo Configuration que representa a hierarquia de configuração a que pertence a instância atual ConfigurationElement . (Herdado de ConfigurationElement) |
| DefaultProvider |
Obtém ou define o fornecedor padrão. |
| DisableExpiration |
Recebe ou define um valor que indica se a expiração da cache está desativada. |
| DisableMemoryCollection |
Recebe ou define um valor que indica se a coleção de memória cache está desativada. |
| ElementInformation |
Obtém um ElementInformation objeto que contém a informação e funcionalidade não personalizáveis do ConfigurationElement objeto. (Herdado de ConfigurationElement) |
| ElementProperty |
Obtém o ConfigurationElementProperty objeto que representa o ConfigurationElement próprio objeto. (Herdado de ConfigurationElement) |
| EvaluationContext |
Obtém o ContextInformation objeto para o ConfigurationElement objeto. (Herdado de ConfigurationElement) |
| HasContext |
Obtém um valor que indica se a CurrentConfiguration propriedade é |
| Item[ConfigurationProperty] |
Obtém ou define uma propriedade ou atributo deste elemento de configuração. (Herdado de ConfigurationElement) |
| Item[String] |
Obtém ou define uma propriedade, atributo ou elemento filho deste 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 |
Recebe ou define um valor que indica se o elemento está bloqueado. (Herdado de ConfigurationElement) |
| PercentagePhysicalMemoryUsedLimit |
Recebe ou define um valor que indica a percentagem máxima de utilização da memória virtual. |
| PrivateBytesLimit |
Obtém ou define um valor que indica o tamanho máximo do espaço privado do processo de trabalho. |
| PrivateBytesPollTime |
Recebe ou define um valor que indica o intervalo de tempo entre sondagens para a utilização da memória do processo de trabalho. |
| Properties |
Recebe a coleção de propriedades. (Herdado de ConfigurationElement) |
| Providers |
Obtém a coleção de definições do fornecedor. |
| SectionInformation |
Obtém um SectionInformation objeto que contém a informação e funcionalidade não personalizáveis do ConfigurationSection objeto. (Herdado de ConfigurationSection) |
Métodos
| Name | Description |
|---|---|
| DeserializeElement(XmlReader, Boolean) |
Lê XML a partir do ficheiro de configuração. (Herdado de ConfigurationElement) |
| DeserializeSection(XmlReader) |
Lê XML a partir do ficheiro de configuração. (Herdado de ConfigurationSection) |
| Equals(Object) |
Compara a instância atual ConfigurationElement com o objeto especificado. (Herdado de ConfigurationElement) |
| GetHashCode() |
Obtém um valor único que representa a instância atual ConfigurationElement . (Herdado de ConfigurationElement) |
| GetRuntimeObject() |
Devolve um objeto personalizado quando sobrescrito numa classe derivada. (Herdado de ConfigurationSection) |
| GetTransformedAssemblyString(String) |
Devolve a versão transformada do nome da assembleia especificado. (Herdado de ConfigurationElement) |
| GetTransformedTypeString(String) |
Devolve 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 ConfigurationElement objeto para o seu estado inicial. (Herdado de ConfigurationElement) |
| InitializeDefault() |
Usado para inicializar um conjunto padrão de valores para o ConfigurationElement objeto. (Herdado de ConfigurationElement) |
| IsModified() |
Indica se este elemento de configuração foi modificado desde a última vez que foi guardado ou carregado quando implementado numa classe derivada. (Herdado de ConfigurationSection) |
| IsReadOnly() |
Recebe um valor que indica se o ConfigurationElement objeto é apenas de leitura. (Herdado de ConfigurationElement) |
| ListErrors(IList) |
Adiciona os erros de propriedades inválidas neste ConfigurationElement objeto, e em todos os subelementos, à lista passada. (Herdado de ConfigurationElement) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| OnDeserializeUnrecognizedAttribute(String, String) |
Recebe 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) |
Lança uma exceção quando uma propriedade exigida não é encontrada. (Herdado de ConfigurationElement) |
| PostDeserialize() |
Chamada após desserialização. (Herdado de ConfigurationElement) |
| PreSerialize(XmlWriter) |
Chamado antes da serialização. (Herdado de ConfigurationElement) |
| Reset(ConfigurationElement) |
Reinicia o estado interno do ConfigurationElement objeto, incluindo os bloqueios e as coleções de propriedades. (Herdado de ConfigurationElement) |
| ResetModified() |
Redefine o valor do IsModified() método para |
| SerializeElement(XmlWriter, Boolean) |
Escreve o conteúdo deste elemento de configuração no ficheiro de configuração quando implementado numa classe derivada. (Herdado de ConfigurationElement) |
| SerializeSection(ConfigurationElement, String, ConfigurationSaveMode) |
Cria uma string XML contendo uma vista não fundida do ConfigurationSection objeto como uma única secção para escrever num ficheiro. (Herdado de ConfigurationSection) |
| SerializeToXmlElement(XmlWriter, String) |
Escreve as etiquetas exteriores deste elemento de configuração no ficheiro de configuração quando implementado numa classe derivada. (Herdado de ConfigurationElement) |
| SetPropertyValue(ConfigurationProperty, Object, Boolean) |
Define uma propriedade para o valor especificado. (Herdado de ConfigurationElement) |
| SetReadOnly() |
Define a IsReadOnly() propriedade para o ConfigurationElement objeto e todos os subelementos. (Herdado de ConfigurationElement) |
| ShouldSerializeElementInTargetVersion(ConfigurationElement, String, FrameworkName) |
Indica se o elemento especificado deve ser serializado quando a hierarquia de objetos de configuração é serializada para a versão alvo 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 alvo 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 alvo especificada do .NET Framework. (Herdado de ConfigurationSection) |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |
| Unmerge(ConfigurationElement, ConfigurationElement, ConfigurationSaveMode) |
Modifica o ConfigurationElement objeto para remover todos os valores que não deveriam ser guardados. (Herdado de ConfigurationElement) |