Adam
Adam

Reputation: 735

Simple .exe using 50% CPU using System.Threading

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

Answers (2)

Ioannis Karadimas
Ioannis Karadimas

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

SLaks
SLaks

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

Related Questions