gpt4 book ai didi

c# - 我需要保留对 FileSystemWatcher 的引用吗?

转载 作者:太空狗 更新时间:2023-10-29 17:49:48 26 4
gpt4 key购买 nike

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

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) 设置观察器是否安全?或者我应该在私有(private)字段中保留对它的引用以防止它被垃圾收集?

最佳答案

在上面的示例中,FileSystemWatcher 保持事件状态只是因为属性 EnableRaisingEvents 设置为 true。 Singleton 类有一个事件处理程序注册到 FileSystemWatcher.Changed 事件这一事实对 fsw 是否符合垃圾收集条件没有任何直接影响。参见 Do event handlers stop garbage collection from occurring?获取更多信息。

下面的代码显示当 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);
}
}

关于c# - 我需要保留对 FileSystemWatcher 的引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9110617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com