处置FileSystemWatcher [英] Disposing of FileSystemWatcher
问题描述
因此,我的理解是,每当使用实现IDisposable的类时,其父级也需要实现IDisposable接口。 (使用FileSystemWatcher的FileWatcher)
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;
}
推荐答案
是,实施<$ c在这种情况下,$ c> IDisposable 是正确的解决方案(我认为)。您的对象是长期存在的,并且必须超出任何特定函数调用的范围,因此所有函数作用域级别的解决方案(使用
,尝试。
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屋!