2012-02-02 39 views
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)?或者我应该在私人领域中引用它以防止它被垃圾收集?

回答

6

在上面的示例中,FileSystemWatcher仅因为属性EnableRaisingEvents设置为true而保持有效。 Singleton类具有注册为FileSystemWatcher.Changed事件的事件处理程序的事实与fsw没有任何直接关系,因此符合垃圾回收的条件。有关更多信息,请参阅Do event handlers stop garbage collection from occurring?

下面的代码显示与EnableRaisingEvents设置为false,所述FileSystemWatcher对象作为垃圾回收:一旦GC.Collect()被调用时,IsAlive属性上WeakReferencefalse

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); 
    } 
} 
+0

我可以找到没有文件说'EnableRaisingEvents'对垃圾回收有任何影响。我认为需要一个本地字段来确保'FileSystemWatcher'没有被垃圾回收。 – Lukazoid 2012-02-03 00:32:47

+0

我已经编辑了我的答案,并显示了一个示例,显示如果EnableRaisingEvents为false,FileSystemWatcher将被垃圾收集。 – 2012-02-03 01:02:13

+0

感谢你的这一点,我确实希望这个功能在MSDN上有记录,它看起来很容易结束一些悬挂的'FileSystemWatcher's。 – Lukazoid 2012-02-03 01:14:27

相关问题