处置FileSystemWatcher

Sha*_*eKm 3 .net c# filesystemwatcher .net-4.5

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

因此,在使用FileSystemWatcher时,处置FileSystemWatcher的正确方法是什么?我希望在关闭应用程序之前不处理/(监视)FileWatcher。

我会使用“负责任的所有者模式”吗(尝试/最终)还是其他?我的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;
    }
Run Code Online (Sandbox Code Playgroud)

xxb*_*bcc 5

是的,IDisposable在这种情况下,实施是正确的解决方案(我认为)。你的目的是寿命长,具有现场以外的任何特定函数调用的范围,使所有功能范围级解决方案(usingtry..finally,等)都出来了。

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