我需要保留对 FileSystemWatcher 的引用吗?
我正在使用 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
)设置观察程序是否安全?或者我应该在私有字段中保留对它的引用以防止它被垃圾收集?
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:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在上面的示例中,
FileSystemWatcher
之所以保持活动状态,只是因为属性EnableRaisingEvents
设置为true
。事实上,Singleton 类有一个注册到FileSystemWatcher.Changed
事件的事件处理程序,这对于fsw
是否有资格进行垃圾回收没有任何直接影响。有关详细信息,请参阅事件处理程序是否会阻止垃圾回收的发生?信息。以下代码显示,将
EnableRaisingEvents
设置为false
时,FileSystemWatcher
对象将被垃圾回收:一旦GC.Collect() 时,
WeakReference
上的IsAlive
属性为false
。In the example above
FileSystemWatcher
is kept alive only because the propertyEnableRaisingEvents
is set totrue
. The fact that the Singleton class has an event handler registered toFileSystemWatcher.Changed
event does not have any direct bearing onfsw
being eligible for Garbage collection. See Do event handlers stop garbage collection from occurring? for more information.The following code shows that with
EnableRaisingEvents
set tofalse
, theFileSystemWatcher
object is garbage collected: OnceGC.Collect()
is called, theIsAlive
property on theWeakReference
isfalse
.