处理 FileSystemWatcher [英] Disposing of FileSystemWatcher
问题描述
所以我的理解是,每当使用实现 IDisposable 的类时,它的父级也需要实现 IDisposable 接口.(FileWatcher 使用 FileSystemWatcher)
So my understanding is that whenever using a class that implements IDisposable, it's parent also needs to implement IDisposable interface. (FileWatcher using FileSystemWatcher)
那么在使用 FileSystemWatcher 时,处理 FileSystemWatcher 的正确方法是什么?我希望 FileWatcher 在应用程序关闭之前不被处理/(观看).
So when using FileSystemWatcher what is the proper way of disposing of FileSystemWatcher? I want FileWatcher not to be disposed/(watching) until application is closed.
我会使用负责任的所有者模式吗?(尝试/最后)还是其他什么?我的 FileWatcher 也应该实现 IDisposable 吗?我将无法使用 using{},因为这个 fileWatcher 应该在应用程序运行的整个过程中监视文件更改.处理这种情况的正确方法是什么?
Would I use Responsible Owner Pattern?(try/finally) or something else? Should my FileWatcher also implement IDisposable? I won't be able to use using{} since this fileWatcher should be watching the file changes the whole time application runs. What is the proper way of handling this scenario?
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
是正确的解决方案.您的对象是长期存在的,并且必须存在于任何特定函数调用的范围之外,因此所有函数范围级别的解决方案(using
、try..finally
等)出来了.
Yes, implementing IDisposable
is the right solution in this case (in my opinion). Your object is long-lived and has to live outside the scope of any particular function call so all function-scope level solutions (using
, try..finally
, etc.) are out.
为此,IDisposable
是 .NET 中的标准模式,您可以在处理 FileWatcher
时轻松处理嵌套对象.
For this, IDisposable
is a standard pattern in .NET and you can easily dispose of the nested object when FileWatcher
is disposed of.
这篇关于处理 FileSystemWatcher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!