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

M4N*_*M4N 9 c# asp.net garbage-collection 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...
}
Run Code Online (Sandbox Code Playgroud)

到目前为止一切正常.但我的问题是:

使用局部变量(var fsw)设置观察者是否安全?或者我应该在私有字段中保留它的引用,以防止它被垃圾收集?

小智 9

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

以下代码显示,如果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);
    }
}
Run Code Online (Sandbox Code Playgroud)