因此,我的理解是,每当使用实现IDisposable的类时,它的父类也需要实现IDisposable接口。(FileWatcher使用FileSystemWatcher)
那么,在使用FileSystemWatcher时,如何正确地处理FileSystemWatcher呢?我希望FileWatcher在申请关闭之前不会被处理/(观看)。
我会使用负责任的所有者模式吗?(尝试/最后)还是其他什么?我的FileWatcher也应该实现IDisposable吗?我将无法使用{},因为这个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;
}发布于 2015-11-03 20:48:11
是的,在这种情况下,实现IDisposable是正确的解决方案(在我看来)。您的对象寿命很长,必须在任何特定函数调用的作用域之外存在,因此所有函数作用域级别的解决方案(using、try..finally等)都出去了。
为此,IDisposable是.NET中的一个标准模式,当FileWatcher被释放时,您可以轻松地处理嵌套的对象。
发布于 2015-11-03 21:04:23
关闭应用程序时,运行dispose方法。
根据所要求的方法,当你想要在你关闭程序的时候处理一些东西。
如果您使用的是一个类,那么IDisposable是用来释放类对象的,但是实际上,当您关闭程序时,您可能仍然希望这样做。
bool myFlag = false;
private FileSystemWatcher watcher;
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
myFlag = true;
if(myFlag)
watcher.Dispose(); //Your FileSystemWatcher object
}https://stackoverflow.com/questions/33508669
复制相似问题