Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 948
Adam Avatar asked Jun 26 '26 17:06

Adam


1 Answers

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).

like image 194
SLaks Avatar answered Jun 29 '26 06:06

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!