Friday, April 22, 2011

FileSystemWatcher OnChange event fires twice

THIS IS A KNOWN BUG.

So here's what I did to deal with this:


I am only monitoring 1 file (a config file for a service, so it can update without having be restarted). The way I solved the 2 onchanged event firing problem is like this:

internal class ConfigFileWatcher
{
    private FileSystemWatcher fileSysWatcher;
    private bool eventFired;
    internal ConfigFileWatcher()
   {
      eventFired = false;
     //initialize fileSysWatcher with path and filter, and add OnChange event handler
   }
        private void fileSysWatcher_Changed(object sender, System.IO.FileSystemEventArgs e)
        {
            if (eventFired)
            {
                eventFired = false;
                return;
            }
            else
                eventFired = true;
           
            //do stuff with the file
}
}

Since we know for sure that the OnChange event is going to fire twice, it makes sense to use a bool like this.

I know this isn't what your problem is exactly, but maybe you could experiment by using a Dictionary with FullPath = key, EventFired Bool = value

So for example, Dictionary<string, bool> eventFireDict

In the OnChanged event check for that full path

//pseudo-code
if(Dictionary Contains Full Path)
{
  if (Key's Value = True)
   {
    set key's value to False
    return
   }
   else
  {
     set key's value to True
   }
}
else
Insert <Full Path, True> into Dictionary
}

Notice, you don't even need a Dictioanry<string, bool> if you're only looking for a change in that file once. If you're just looking for a change once, I'm pretty sure you could just use a List<string> like this

//pseudo-code

if(List<string> contains Full Path)
{
//event already fired for this full path, so remove the full path and return so it doesn't process that file //twice
List.remove(Full Path);
return;
}
else
{
//event hasn't fired yet for this Full Path, so put it in the List and then process the Full Path
List.add(Full Path);
process(Full Path);
}


References
http://weblogs.asp.net/ashben/archive/2003/10/14/31773.aspx

No comments:

Post a Comment

There was an error in this gadget