8
我正在使用FileSystemWatcher
(在ASP.NET Web应用程序中)来监视文件以进行更改。观察者设置在Singleton类的构造函数中,例如:我是否需要保留对FileSystemWatcher的引用?
private SingletonConstructor()
{
var fileToWatch = "{absolute path to file}";
var fsw = new FileSystemWatcher(
Path.GetDirectoryName(fileToWatch),
Path.GetFileName(fileToWatch));
fsw.Changed += OnFileChanged;
fsw.EnableRaisingEvents = true;
}
private void OnFileChanged(object sender, FileSystemEventArgs e)
{
// process file...
}
到目前为止一切正常。但我的问题是:
使用本地变量设置观察器安全吗(var fsw
)?或者我应该在私人领域中引用它以防止它被垃圾收集?
我可以找到没有文件说'EnableRaisingEvents'对垃圾回收有任何影响。我认为需要一个本地字段来确保'FileSystemWatcher'没有被垃圾回收。 – Lukazoid 2012-02-03 00:32:47
我已经编辑了我的答案,并显示了一个示例,显示如果EnableRaisingEvents为false,FileSystemWatcher将被垃圾收集。 – 2012-02-03 01:02:13
感谢你的这一点,我确实希望这个功能在MSDN上有记录,它看起来很容易结束一些悬挂的'FileSystemWatcher's。 – Lukazoid 2012-02-03 01:14:27