Lock Loops Vs Soft Spikes
Writing an infinite loop is simple:
As an engineer, my intuition (and my experiments) indicate that spikes makes no sense whatsoever (edit: and I have Mr Newton and a bunch of other like really old guys hinting that my intuition aligns pretty well with with their work -work that kinda was essential to putting a man on the moon which allegedly worked out pretty OK). A bunch of spikes screwed tightly into a normal sized speaker. Soft Spikes Hair Curlers. Soft Spike Hair Curlers are the Original self-locking hair curlers. Designed with a self-locking loop that will not. Amazon (folica was cheaper). And it's Shawnta715 who had the video soft spikes vs loc loops. Timers are also a solution, but the code behind a timer is also an infinity loop - I would assume - that fires your code on elapsed intervals, but they have the correct infinity-loop setup. If you need a large sleep, you can cut it into smaller sleeps. So something like this is a simple and easy 0% CPU solution for a non-UI app.
But this will trash the CPU performance. This execution thread will take as much as possible from CPU's power.
What is the best way to lower the impact on CPU?Adding some Thread.Sleep(n)
should do the trick, but setting a high timeout value for Sleep()
method may indicate an unresponsive application to the operating system.
Let's say I need to perform a task each minute or so in a console app.I need to keep Main()
running in an 'infinite loop' while a timer will fire the event that will do the job. I would like to keep Main()
with the lowest impact on CPU.
What methods do you suggest. Sleep()
can be ok, but as I already mentioned, this might indicate an unresponsive thread to the operating system.
LATER EDIT:
I want to explain better what I am looking for:
I need a console app not Windows service. Console apps can simulate the Windows services on Windows Mobile 6.x systems with Compact Framework.
I need a way to keep the app alive as long as the Windows Mobile device is running.
We all know that the console app runs as long as its static Main() function runs, so I need a way to prevent Main() function exit.
In special situations (like: updating the app), I need to request the app to stop, so I need to infinitely loop and test for some exit condition. For example, this is why
Console.ReadLine()
is no use for me. There is no exit condition check.Regarding the above, I still want Main() function as resource friendly as possible. Let asside the fingerprint of the function that checks for the exit condition.
11 Answers
To avoid the infinity loop simply use a WaitHandle
. To let the process be exited from the outer world use a EventWaitHandle
with a unique string. Below is an example.
If you start it the first time, it simple prints out a message every 10 seconds. If you start in the mean time a second instance of the program it will inform the other process to gracefully exit and exits itself also immediately. The CPU usage for this approach: 0%
OliverOliverYou can use System.Threading.Timer Class which provides ability to execute callback asynchronously in a given period of time.
As alternative there is System.Timers.Timer class which exposes Elapsed Event which raises when a given period of time is elapsed.
sllsllWhy would you condone the use of an infinite loop? For this example would setting the program up as a scheduled task, to be run every minute, not be more economical?
anothershruberyanothershruberyWhy don't you write a small application and use the system's task scheduler to run it every minute, hour...etc?
Another option would be to write a Windows Service which runs in the background. The service could use a simple Alarm class like the following on MSDN:
You can use it to periodically trigger your method. Internally this Alarm class uses a timer:
Just set the timer's interval correctly (e.g. 60000 milliseconds) and it will raise the Elapsed event periodically. Attach an event handler to the Elapsed event to perform your task. No need to implement an 'infinite loop' just to keep the application alive. This is handled for you by the service.
Christophe GeersChristophe GeersIt sounds to me like you want Main() to enter an interruptable loop. For this to happen, multiple threads must be involved somewhere (or your loop must poll periodically; I am not discussing that solution here though). Either another thread in the same application, or a thread in another process, must be able to signal to your Main() loop that it should terminate.
If this is true, then I think you want to use a ManualResetEvent or an EventWaitHandle . You can wait on that event until it is signalled (and the signalling would have to be done by another thread).
For example:
Matthew WatsonMatthew WatsonYou can use Begin-/End-Invoke
to yield to other threads. E.g.
You would use it as such:
This used 60% of one core on my machine (completely empty loop). Alternatively, you can use this (Source) code in the body of your loop:
That used 20% of one core on my machine.
Jonathan DickinsonJonathan DickinsonTo expound on a comment CodeInChaos made:
You can set a given thread's priority. Threads are scheduled for execution based on their priority. The scheduling algorithm used to determine the order of thread execution varies with each operating system. All threads default to 'normal' priority, but if you set your loop to low; it shouldn't steal time from threads set to normal.
I did this for an application that had to process files as they were dropped on a folder. Your best bet is a timer (as suggested) with a Console.ReadLine() at the end of 'main' without putting in a loop.
Now, your concern about telling the app to stop:
I have also done this via some rudimentary 'file' monitor. Simply creating the file 'quit.txt' in the root folder of the application (by either my program or another application that might request it to stop) will make the application quit. Semi-code:
Best Way To Curl Sisterlocks
The OnNewFile could be something like this:
Now you mentioned that this is (or could be) for a mobile application? You might not have the file system watcher. In that case, maybe you just need to 'kill' the process (you said 'In special situations (like: updating the app), I need to request the app to stop'. Whoever the 'requester' to stop it is, should simply kill the process)
Lock Loops Vs Soft Spikes For Sale
The Timer approach is probably your best bet, but since you mention Thread.Sleep there is an interesting Thread.SpinWait or SpinWait struct alternative for similar problems that can sometimes be better than short Thread.Sleep invocations.
Also see this question: What's the purpose of Thread.SpinWait method?
Lots of 'advanced' answers here but IMO simply using a Thread.Sleep(lowvalue) should suffice for most.
Timers are also a solution, but the code behind a timer is also an infinity loop - I would assume - that fires your code on elapsed intervals, but they have the correct infinity-loop setup.
If you need a large sleep, you can cut it into smaller sleeps.
So something like this is a simple and easy 0% CPU solution for a non-UI app.
Regarding how the OS detects if the app is unresponsive. I do not know of any other tests than on UI applications, where there are methods to check if the UI thread processes UI code. Thread sleeps on the UI will easily be discovered. The Windows 'Application is unresponsive' uses a simple native method 'SendMessageTimeout' to see detect if the app has an unresponse UI.
Any infinity loop on an UI app should always be run in a separate thread.
Wolf5Lock Loops Vs Soft Spikes For Men
Wolf5To keep console applications running just add a Console.ReadLine()
to the end of your code in Main()
.
If the user shouldn't be able to terminate the application you can do this with a loop like the following: