Reputation: 735
I have a very simple executable that check a specific folder about every 3 seconds to see if there is a file(s) in there. If it finds a file(s) it does something and then returns to checking the folder every 3 seconds.
People have reported that at times this executable is taking up 50% of their CPU, is there any suggestions on how do this properly. Below is sample code of how I am doing this.
// Check our folder every x seconds
Timer = new System.Threading.Timer(TimerCallback, null, 0, Global.SecondsToCheckPrintFolder * 1000);
Upvotes: 3
Views: 519
Reputation: 7896
This executes inside a thread pool, which means that the callback can be executed multiple simultaneous times. Why not use a simple loop, like so?
while(true)
{
if (File.Exists(@"someFile"))
{
// Do stuff
}
Thread.Sleep(3000);
}
Upvotes: 1
Reputation: 887433
You should use a FileSystemWatcher
.
To answer your question, your main thread is probably running while(true) { }
, which will kill the CPU forever.
To make the main thread wait forever, you should call Application.Run()
.
You could also call Thread.Sleep(-1)
.
Upvotes: 9