我需要保持在FileSystemWatcher的参考? [英] Do I need to keep a reference to a FileSystemWatcher?

查看:163
本文介绍了我需要保持在FileSystemWatcher的参考?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 FileSystemWatcher的(在ASP.NET Web应用程序)来监视更改的文件。观察者是建立在一个Singleton类的构造函数,例如:

I'm using a FileSystemWatcher (in an ASP.NET web app) to monitor a file for changes. The watcher is set up in the constructor of a Singleton class, e.g:

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...
}

一切工作正常为止。但我的问题是:

Everything works fine so far. But my question is:

它是安全的安装使用一个局部变量的守望者( VAR FSW )?或者我应该保持对它的引用在私人领域,以防止它被垃圾收集?

Is it safe to setup the watcher using a local variable (var fsw)? Or should I keep a reference to it in a private field to prevent it from being garbage collected?

推荐答案

在上面<例子code> FileSystemWatcher的保持活着,只是因为财产 EnableRaisingEvents 设置为真正。该辛格尔顿类有注册到 FileSystemWatcher.Changed 的事件处理程序的事实,事件不会对 FSW 任何直接关系是符合垃圾回收。请参见做的事件处理程序,从停止存在的垃圾收集?了解信息。

In the example above FileSystemWatcher is kept alive only because the property EnableRaisingEvents is set to true. The fact that the Singleton class has an event handler registered to FileSystemWatcher.Changed event does not have any direct bearing on fsw being eligible for Garbage collection. See Do event handlers stop garbage collection from occuring? for more information.

下面的代码表明,与 EnableRaisingEvents 设置为 FileSystemWatcher的对象进行垃圾回收:一旦 GC.Collect的()被调用时,的IsAlive 的WeakReference

The following code shows that with EnableRaisingEvents set to false, the FileSystemWatcher object is garbage collected: Once GC.Collect() is called, the IsAlive property on the WeakReference is 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);
    }
}

这篇关于我需要保持在FileSystemWatcher的参考?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆