Do I need to save a link to FileSystemWatcher?

I am using FileSystemWatcher (in an ASP.NET web application) to monitor a file for changes. The observer is configured in the constructor of the Singleton class, for example:

 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 perfectly. But my question is:

Is it safe to configure an observer with a local variable ( var fsw )? Or should I keep the link to it in a private field to prevent garbage collection?

+8
garbage-collection c # filesystemwatcher
source share
1 answer

In the above example, FileSystemWatcher is only supported because the EnableRaisingEvents property EnableRaisingEvents set to true . The fact that the Singleton class has an event handler registered in the FileSystemWatcher.Changed event is not directly related to fsw , which has the right to collect garbage. See To process event handlers, stop garbage collection .

The following code shows that with EnableRaisingEvents set to false , the FileSystemWatcher object is garbage collection: after calling GC.Collect() IsAlive property in 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); } } 
+6
source share

All Articles