我是否需要保留对FileSystemWatcher的引用?

我正在使用FileSystemWatcher (在ASP.NET Web应用程序中)监视文件以进行更改。 观察者在Singleton类的构造函数中设置,例如:

 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 )设置观察者是否安全? 或者我应该在私人领域中保留它的引用,以防止它被垃圾收集?

在上面的示例中, FileSystemWatcher仅保持活动状态,因为属性EnableRaisingEvents设置为true 。 Singleton类具有向FileSystemWatcher.Changed事件注册的事件处理程序的事实对fsw没有任何直接影响符合垃圾收集条件。 请参阅事件处理程序停止垃圾收集发生? 欲获得更多信息。

以下代码显示,如果将EnableRaisingEvents设置为false ,则会对FileSystemWatcher对象进行垃圾回收: GC.Collect()WeakReference上的IsAlive属性为false

 class MyClass { public WeakReference FileSystemWatcherWeakReference; public MyClass() { var fileToWatch = @"d:\temp\test.txt"; var fsw = new FileSystemWatcher( Path.GetDirectoryName(fileToWatch), Path.GetFileName(fileToWatch)); fsw.Changed += OnFileChanged; fsw.EnableRaisingEvents = false; FileSystemWatcherWeakReference = new WeakReference(fsw); } private void OnFileChanged(object sender, FileSystemEventArgs e) { // process file... } } class Program { static void Main(string[] args) { MyClass mc = new MyClass(); GC.Collect(); Console.WriteLine(mc.FileSystemWatcherWeakReference.IsAlive); } }