首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我需要保留对FileSystemWatcher的引用吗?

我需要保留对FileSystemWatcher的引用吗?
EN

Stack Overflow用户
提问于 2012-02-02 18:21:37
回答 1查看 1.8K关注 0票数 10

我正在使用FileSystemWatcher (在ASP.NET web应用程序中)监视文件的更改。监视器是在单例类的构造函数中设置的,例如:

代码语言:javascript
复制
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)设置监视器是否安全?或者我应该在私有字段中保留对它的引用,以防止它被垃圾收集?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-02-03 08:25:09

在上面的示例中,FileSystemWatcher保持活动状态的唯一原因是属性EnableRaisingEvents被设置为true。Singleton类有一个注册到FileSystemWatcher.Changed事件的事件处理程序,这一事实与fsw是否有资格进行垃圾回收没有任何直接关系。有关详细信息,请参阅Do event handlers stop garbage collection from occurring?

下面的代码显示当EnableRaisingEvents设置为false时,将对FileSystemWatcher对象进行垃圾回收:调用GC.Collect()后,WeakReference上的IsAlive属性将为false

代码语言:javascript
复制
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);
    }
}
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9110617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档