FileSystemWatcher.WaitForChanged surprising (wrong?) behaviour

  • Thread starter Thread starter John Aldridge
  • Start date Start date
J

John Aldridge

I'm trying to use the System.IO.FileSystemWatcher class in code like...

using (FileSystemWatcher changeMonitor = new FileSystemWatcher("."))
{
for (; ; )
{
WaitForChangedResult c = changeMonitor.WaitForChanged(
WatcherChangeTypes.Created, 60 * 1000);

Console.WriteLine ("Creation");
}
}

and the code works as expected unless a file change /other/ than a
creation occurs in the folder, at which point the WaitForChanged call no
longer returns even after another creation.

So, in an empty folder

echo >a.txt ("Creation" is printed)
echo >b.txt ("Creation" is printed)
dele b.txt (nothing happens, as expected)
echo >c.txt (** nothing happens ... why? **)

Is this the intended behaviour? It seems rather surprising!

I note that if I change the code to pass WatcherChangeTypes.All, then
the code works as expected, but I get notification of changes I'm not
interested in.
 
Hi John,

I was able to repro that behavior and it seems like a bug to me. You should
think about notifying Microsoft :)

Here's a work-around for you in the mean-time:

// 2.0 framework code:

using (FileSystemWatcher changeMonitor = new FileSystemWatcher("."))
{
System.Threading.EventWaitHandle wait =
new System.Threading.EventWaitHandle(false,
System.Threading.EventResetMode.AutoReset);

string createdFile = null;

changeMonitor.EnableRaisingEvents = true;
changeMonitor.Created +=
delegate(object sender, FileSystemEventArgs e)
{
createdFile = e.FullPath;
wait.Set();
};

while (true) // personal preference ;)
{
if (wait.WaitOne(60 * 1000, false))
{
Console.WriteLine(createdFile);
}
}
}
 
Back
Top