我正在使用一个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...
}
到目前为止一切正常。但我的问题是:
使用局部变量设置观察程序是否安全(var fsw
)?或者我应该在私有字段中保留对它的引用以防止它被垃圾收集?
在上面的例子中FileSystemWatcher
仅仅因为财产而得以生存EnableRaisingEvents
被设定为true
。事实上,Singleton 类有一个事件处理程序注册到FileSystemWatcher.Changed
事件没有任何直接影响fsw
符合垃圾收集资格。看事件处理程序是否会阻止垃圾收集的发生? https://stackoverflow.com/questions/298261/do-event-handlers-stop-garbage-collection-from-occuring了解更多信息。
下面的代码显示了EnableRaisingEvents
设置false
, the FileSystemWatcher
对象被垃圾回收:一次GC.Collect()
被称为,IsAlive
财产在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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)