Search code examples
c#eventshandlerfilesystemwatcher

FileSystemWatcher remove event handler


For some reason I can not remove an event handler from the FileSystemWatcher.

This is what I have

void Start()
{
     ivFileSystemWatcher = new FileSystemWatcher();
     ivFileSystemWatcher.Changed += 
        new FileSystemEventHandler(ivFileSystemWatcher_Changed);
}

void Stop()
{
     ivFileSystemWatcher.Changed -= 
        new FileSystemEventHandler(ivFileSystemWatcher_Changed);
     ivFileSystemWatcher.Dispose();
}

When I call start I start receiving the change events, but when I call stop I am expecting the events to stop but they are still being raised.


Solution

  • Have you tried setting EnableRaisingEvents to false:

    void Stop() 
    { 
         ivFileSystemWatcher.EnableRaisingEvents = false;
    
         ivFileSystemWatcher.Changed -=  
            new FileSystemEventHandler(ivFileSystemWatcher_Changed); 
         ivFileSystemWatcher.Dispose(); 
    }
    

    Without seeing the rest of your code, I'm not convinced that's the best place for the Dispose()...