我正在使用FileSystemWatcher (在ASP.NET web应用程序中)监视文件的更改。监视器是在单例类的构造函数中设置的,例如:
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)设置监视器是否安全?或者我应该在私有字段中保留对它的引用,以防止它被垃圾收集?
发布于 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。
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);
}
}https://stackoverflow.com/questions/9110617
复制相似问题