Csharp/C#教程:我是否需要保留对FileSystemWatcher的引用?分享


我是否需要保留对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 )设置观察者是否安全? 或者我应该在私人领域中保留它的引用,以防止它被垃圾收集?

在上面的示例中, FileSystemWatcher仅保持活动状态,因为属性EnableRaisingEvents设置为true 。 Singleton类具有向FileSystemWatcher.Changed事件注册的事件处理程序的事实对fsw没有任何直接影响符合垃圾收集条件。 请参阅事件处理程序停止垃圾收集发生? 欲获得更多信息。

以下代码显示,如果将EnableRaisingEvents设置为false ,则会对FileSystemWatcher对象进行垃圾回收: GC.Collect()WeakReference上的IsAlive属性为false

上述就是C#学习教程:我是否需要保留对FileSystemWatcher的引用?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 class MyClass { public WeakReference FileSystemWatcherWeakReference; public MyClass() { var fileToWatch = @"d:temptest.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); } } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/987252.html

(0)
上一篇 2021年12月22日
下一篇 2021年12月22日

精彩推荐