FileChangeMonitor Classe
Definição
Representa um objeto que monitora alterações nos arquivos.Represents an object that monitors changes to files.
public ref class FileChangeMonitor abstract : System::Runtime::Caching::ChangeMonitor
public abstract class FileChangeMonitor : System.Runtime.Caching.ChangeMonitor
type FileChangeMonitor = class
inherit ChangeMonitor
Public MustInherit Class FileChangeMonitor
Inherits ChangeMonitor
- Herança
- Derivado
Exemplos
O exemplo a seguir mostra como criar um item de cache que usa um HostFileChangeMonitor objeto para monitorar o estado dos dados de origem (um arquivo) no sistema de arquivos.The following example shows how to create a cache item that uses a HostFileChangeMonitor object to monitor the state of the source data (a file) on the file system. A classe HostFileChangeMonitor herda da classe FileChangeMonitor.The HostFileChangeMonitor class inherits from the FileChangeMonitor class. A entrada de cache é definida usando um CacheItemPolicy objeto que fornece detalhes de remoção e expiração para a entrada de cache.The cache entry is defined using a CacheItemPolicy object that provides eviction and expiration details for the cache entry.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Runtime.Caching;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Button1_Click1(object sender, EventArgs e)
{
ObjectCache cache = MemoryCache.Default;
string fileContents = cache["filecontents"] as string;
if (fileContents == null)
{
CacheItemPolicy policy = new CacheItemPolicy();
policy.AbsoluteExpiration =
DateTimeOffset.Now.AddSeconds(10.0);
List<string> filePaths = new List<string>();
string cachedFilePath = Server.MapPath("~") +
"\\cacheText.txt";
filePaths.Add(cachedFilePath);
policy.ChangeMonitors.Add(new
HostFileChangeMonitor(filePaths));
// Fetch the file contents.
fileContents = File.ReadAllText(cachedFilePath) + "\n"
+ DateTime.Now.ToString();
cache.Set("filecontents", fileContents, policy);
}
Label1.Text = fileContents;
}
}
Imports System.Runtime.Caching
Imports System.IO
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim cache As ObjectCache = MemoryCache.Default
Dim fileContents As String = TryCast(cache("filecontents"), _
String)
If fileContents Is Nothing Then
Dim policy As New CacheItemPolicy()
policy.AbsoluteExpiration = _
DateTimeOffset.Now.AddSeconds(10.0)
Dim filePaths As New List(Of String)()
Dim cachedFilePath As String = Server.MapPath("~") & _
"\cacheText.txt"
filePaths.Add(cachedFilePath)
policy.ChangeMonitors.Add(New _
HostFileChangeMonitor(filePaths))
' Fetch the file contents.
fileContents = File.ReadAllText(cachedFilePath) & _
vbCrLf & DateTime.Now.ToString()
cache.Set("filecontents", fileContents, policy)
End If
Label1.Text = fileContents
End Sub
End Class
Comentários
A FileChangeMonitor classe é um ChangeMonitor tipo base para classes que monitoram alterações em arquivos.The FileChangeMonitor class is a base ChangeMonitor type for classes that monitor changes to files. Para criar um monitor para alterações no sistema de arquivos, você pode herdar dessa classe.To create a monitor for changes in the file system, you can inherit from this class.
Notas aos Implementadores
Para obter informações sobre o contrato de herança que deve ser seguido, consulte a seção observações para herdeiros na ChangeMonitor visão geral da classe.For information about the inheritance contract that must be followed, see the Notes for Inheritors section in the ChangeMonitor class overview.
Construtores
| FileChangeMonitor() |
Inicializa uma nova instância da classe FileChangeMonitor.Initializes a new instance of the FileChangeMonitor class. Esse construtor é chamado de construtores em classes derivadas para inicializar a classe base.This constructor is called from constructors in derived classes in order to initialize the base class. |
Propriedades
| FilePaths |
Obtém uma coleção que contém os caminhos dos arquivos que são monitorados para alterações.Gets a collection that contains the paths of files that are monitored for changes. |
| HasChanged |
Obtém um valor que indica que o estado monitorado pela classe ChangeMonitor foi alterado.Gets a value that indicates that the state that is monitored by the ChangeMonitor class has changed. (Herdado de ChangeMonitor) |
| IsDisposed |
Obtém um valor que indica que a instância derivada de uma classe ChangeMonitor foi descartada.Gets a value that indicates that the derived instance of a ChangeMonitor class is disposed. (Herdado de ChangeMonitor) |
| LastModified |
Obtém um valor que indica a última vez que um arquivo que está sendo monitorado foi alterado.Gets a value that indicates the last time that a file that is being monitored was changed. |
| UniqueId |
Obtém um valor que representa a instância da classe ChangeMonitor.Gets a value that represents the ChangeMonitor class instance. (Herdado de ChangeMonitor) |
Métodos
| Dispose() |
Libera todos os recursos usados pela instância atual da classe ChangeMonitor.Releases all resources that are used by the current instance of the ChangeMonitor class. (Herdado de ChangeMonitor) |
| Dispose(Boolean) |
Libera todos os recursos gerenciados e não gerenciados e todas as referências à instância de ChangeMonitor.Releases all managed and unmanaged resources and any references to the ChangeMonitor instance. Essa sobrecarga deve ser implementada por classes de monitor de alteração derivadas.This overload must be implemented by derived change-monitor classes. (Herdado de ChangeMonitor) |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object. (Herdado de Object) |
| GetHashCode() |
Serve como a função de hash padrão.Serves as the default hash function. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual.Gets the Type of the current instance. (Herdado de Object) |
| InitializationComplete() |
Chamado do construtor de classes derivadas para indicar que a inicialização foi concluída.Called from the constructor of derived classes to indicate that initialization is finished. (Herdado de ChangeMonitor) |
| MemberwiseClone() |
Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object. (Herdado de Object) |
| NotifyOnChanged(OnChangedCallback) |
Chamado pelos implementadores de cache para registrar um retorno de chamada e notificar uma instância de ObjectCache por meio do delegado de OnChangedCallback quando uma dependência tiver sido alterada.Called by Cache implementers to register a callback and notify an ObjectCache instance through the OnChangedCallback delegate when a dependency has changed. (Herdado de ChangeMonitor) |
| OnChanged(Object) |
Chamado por classes derivadas para gerar o evento quando uma dependência é alterada.Called by derived classes to raise the event when a dependency changes. (Herdado de ChangeMonitor) |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object. (Herdado de Object) |