How to have a FileSystemWatcher thread run forever?

Tai Squared picture Tai Squared · Mar 18, 2009 · Viewed 10.8k times · Source

I need to have a FileSystemWatcher run in an infinite loop to monitor a file for changes, but this file will only change every few days, and maybe only once a week. In the MSDN sample of a FileSystemWatcher, there is a loop while the user doesn't enter q at the console:

while(Console.Read()!='q');

I don't want this to be constantly available so it isn't accidentally killed - it has to run with no user intervention in an infinite loop. Do I have to change the loop to

while (true);

so the thread doesn't exit? This alone isn't ideal as it will peg the CPU - adding a Thread.Sleep call would eliminate the CPU load, and in this case, could be a long sleep as the file very rarely changes. Is this the best way to go? How should I make sure this thread remains alive so the FileSystemWatcher can act when a file changes? This is running on a Windows server(with .NET framework version 2.0), so making it a Windows service would be possible if necessary.

Answer

aehiilrs picture aehiilrs · Mar 18, 2009

If this is running on a server, a service seems like a good bet.

If you want something a little more interactive, I have a small application that lives in my system tray to show me when something happens in our Issues folder. It uses the Application.Run() method to keep itself going without the need for a loop, i.e.

class MainEntryClass
{
    static void Main(string[] args)
    {
        FolderAlerter fa = new FolderAlerter(); 
        Application.Run();
    }
}

Then I set up my FileSystemWatcher in FolderAlerter.