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) {
Muath Ali
source share