处理 FileSystemWatcher

Disposing of FileSystemWatcher

所以我的理解是,每当使用实现 IDisposable 的 class 时,它的父级也需要实现 IDisposable 接口。 (FileWatcher 使用 FileSystemWatcher)

那么在使用 FileSystemWatcher 时,正确的处理 FileSystemWatcher 的方法是什么?我希望 FileWatcher 在应用程序关闭之前不被处理/(观看)。

我会使用负责任的所有者模式吗?(try/finally) 还是其他? 我的 FileWatcher 是否也应该实现 IDisposable?我将无法使用 using{},因为这个 fileWatcher 应该在应用程序运行的整个过程中监视文件更改。处理这种情况的正确方法是什么?

public class FileWatcher : IFileWatcher
{
    private FileSystemWatcher watcher;

    public event EventHandler<EventArgs> SettingsChanged;

    public FileWatcher(bool start)
    {
        this.RegisterForChanges();
    }

    public void OnChanged(object source, EventArgs e)
    {
        if (this.SettingsChanged != null)
        {
            this.SettingsChanged(source, new EventArgs());
        }
    }

    private void RegisterForChanges()
    {
        /// more code here etc
        ...
        this.watcher = new FileSystemWatcher
                           {
                               Path = directory, 
                               NotifyFilter =
                                   NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                   | NotifyFilters.FileName | NotifyFilters.DirectoryName, 
                               Filter = fileName
                           };

        // Add event handlers.
        this.watcher.Changed += this.OnChanged;

        // Begin watching.
        this.watcher.EnableRaisingEvents = true;
    }

是的,在这种情况下实施 IDisposable 是正确的解决方案(我认为)。您的对象是长期存在的,并且必须存在于任何特定函数调用的范围之外,因此所有函数范围级别的解决方案(usingtry..finally 等)都已失效。

为此,IDisposable 是 .NET 中的标准模式,您可以在处理 FileWatcher 时轻松处理嵌套对象。

关闭应用程序时,运行 dispose 方法。

根据要求的方法,当你想在关闭程序时处理一些东西。

如果您使用的是 class via,那么 IDisposable 用于处理 class 对象,但本质上您仍然可能希望在关闭程序时执行此操作

bool myFlag = false;
private FileSystemWatcher watcher;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
           myFlag = true;
           if(myFlag)
           watcher.Dispose(); //Your FileSystemWatcher object
 }