gpt4 book ai didi

c# - 处理 FileSystemWatcher

转载 作者:行者123 更新时间:2023-11-30 14:27:12 24 4
gpt4 key购买 nike

所以我的理解是,每当使用实现 IDisposable 的类时,它的父类也需要实现 IDisposable 接口(interface)。 (使用 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;
}

最佳答案

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

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

关于c# - 处理 FileSystemWatcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33508669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com