Reputation: 45
I have created a very simple from example (console) of the filsystemwatcher to listen for changes on a single directory. I have then taken the exact code and used it in a very simple windows form that has just one list box for the console output, but I have spawned it as a thread - the console version uses 0% cpu whereas the same single thread uses 25% ANY Insights as to why ???
THREADED VERSION
Thread pdfWatcher = new Thread(t => startFileWatcher(pdfStoragePath))
{ IsBackground = false };
pdfWatcher.Start();
}
private void startFileWatcher(string pdfOutputPath)
{
statusOutput.Items.Add("Starting Thread : File Watcher...");
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
watcher.Path = pdfOutputPath;
messageStatusWindow("Watching Path : [" + pdfOutputPath + "] For new PDF's");
// Watch for changes in LastAccess and LastWrite times, and
// the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastWrite;
// Only watch text files.
watcher.Filter = "*.pdf";
// Add event handlers.
//watcher.Changed += OnChanged;
watcher.Created += OnCreated;
//watcher.Deleted += OnChanged;
//watcher.Renamed += OnRenamed;
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press 'q' to quit the sample.");
messageStatusWindow("Thread Started : File Watcher");
while (Console.Read() != 'q') ;
}
}
CONSOLE VERSION
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
// Display the proper way to call the program.
Console.WriteLine("Usage: FileWatcher.exe (directory)");
return;
}
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
watcher.Path = args[1];
Console.WriteLine(args[0]);
// Watch for changes in LastAccess and LastWrite times, and
// the renaming of files or directories.
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName
| NotifyFilters.Size;
// Only watch text files.
watcher.Filter = "*.pdf";
// Add event handlers.
watcher.Changed += OnChanged;
watcher.Created += OnCreated;
watcher.Deleted += OnChanged;
watcher.Renamed += OnRenamed;
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press 'q' to quit the sample.");
while (Console.Read() != 'q') ;
}
in a
Upvotes: 0
Views: 1381
Reputation: 84
The line while (Console.Read() != 'q') ;
is consuming all of your cpu. You must eigther use a message pump (no console application) or some kind of wait mechanism like while(Console.Read()!='g') System.Threading.Thread.Sleep(100);
Upvotes: 1