HostFileChangeMonitor

HostFileChangeMonitor 类是 FileChangeMonitor 类型的具体实现。 此类密封,因此无法扩展。 如果要使用现有缓存实现以及监视更改的文件和目录,此类非常有用。

对于每个指定的文件或目录路径,HostFileChangeMonitor 类在发生以下任何更改时触发更改通知:

  • 被监视文件或目录的的名称更改。

  • 指定的文件或目录在创建监视器时不存在,但后来被创建。 换句话说,在被监视项的范围内创建文件或目录。

  • 更改的被监视文件的大小。

  • 被监视文件的内容已更改,或被监视目录的内容已更改。

  • 文件或目录的访问控制列表 (ACL) 已更改。

  • 被监视文件或目录已被删除。

如果被监视的文件或目录同时发生了太多更改,则 HostFileChangeMonitor 实例可能失去特定更改的跟踪。 在此方案中,HostFileChangeMonitor 类触发更改通知。 HostFileChangeMonitor 实例监视某个目录,并且短期内在目录结构的范围内发生了许多更改时,很可能发生此情况。

由于 HostFileChangeMonitor 类的用途只是通知受监控的文件和目录中内容有更改,因此有关特定更改没有捕获到的详细信息并不被认为是重要的。 HostFileChangeMonitor 类的用途在于提供状态已更改的通知,以便逐出缓存项。 由于 HostFileChangeMonitor 类没有明确指明更改了什么,因此内部更改跟踪溢出不相关。

当您向 HostFileChangeMonitor 实例提供路径时,目录和文件路径必须是目录或文件的完整路径。 不允许使用相对路径以及在路径中使用通配符字符。

HostFileChangeMonitor 类用于 ASP.NET 应用程序时,用于访问被监视项的 Windows 标识将是 ASP.NET 应用程序的应用程序标识。 换句话说,应用程序标识将是以下项之一:

  • 进程标识。

  • 配置的应用程序标识。

  • 应用程序从 UNC 共享中运行时的 UNC 凭据。

HostFileChangeMonitor 类用于非 ASP.NET 应用程序时,在内部使用 FileSystemWatcher 类监视文件。 因此,将用于受监视文件或目录的任何访问控制列表 (ACL) 应用于当前线程的 Windows 标识。

举例如:

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) + "
" + DateTime.Now.ToString();
            cache.Set("filecontents", fileContents, policy);
        }
        Label1.Text = fileContents;
    }
}
原文地址:https://www.cnblogs.com/rainnight/p/3231756.html