Reputation: 881
I've written a fairly simple console app to check an Exchange email box every 30 seconds. When it's not running the check routine, it's in an empty do/loop in the Main method just to keep the program running. I find that that is taking a whole lot more of the server's resources (around 50%) than I expected.
Here's the Main method:
Sub Main()
GetSettings()
tmrCheckInterval.Interval = 30000
tmrCheckInterval.Start()
WriteToConsole("Scan app started")
Do
Loop
End Sub
I don't do very many console apps, so I am not sure if this is the most efficient way, and I have struck out with a Google search. Is there an alternative process that will keep the app running without consuming resources?
Thanks...
Upvotes: 0
Views: 195
Reputation: 415735
If you only want this to run every 30 minutes, you are much better off removing the loop entirely and instead setting up a Scheduled Task.
But as to why this code uses so much CPU... the program is doing work. It has a tight loop that never stops and never yields the CPU. It sits near 50% because you have a dual-core CPU and this uses all of one core. If you had a quad-core, it would use 25%. In the bad old single core days, this would use all of the CPU and even bringing up the task manager to kill the app could be challenging. I'm gonna have nightmares tonight remembering those times, so thanks for that.
I know it seems like you set an interval in this code, but that interval only applies to the timer, and is not part of the loop body. You want something more like this:
Sub Main()
GetSettings()
WriteToConsole("Scan app started")
Do
'Remove the timer and call it's elapsed code directly here.
Thread.Sleep(30 * 60 * 1000)
Loop
End Sub
And again, this is still not as good as just using a scheduled task.
Upvotes: 2