c# - Does a while(true) Infinite Loop Peg the CPU? -


i have situation need constant loop running in service, each time checking conditions, , taking action appropriate. design perspective, using while (true) loop fits perfectly:

while (true) {     process(); } 

i have seen references eat unnecessary cpu cycles, , should use timer, or add thread.sleep loop. have seen posts stating there nothing wrong using while (true).

on dev machine, not seem have negative impact, although cpu usage go up. may cpu usage gets spread across multiple cores, deployment environment may have single core.

does while (true) loop have negative performance impact on cpu, , if so, correct way mitigate impact?

edit

the process() method checks state of in-memory (fast) data store. if finds there work based on state, processes using task.run() (so control returns loop immediately).

in cooperative multitasking system, indeed peg cpu (or @ least, 1 core).

however, modern oses employ preemptive multitasking, means os controls how time process gets. although loop use 100% of thread's (or possibly process's) time, , deprive others of some cpu time, os ensure other processes/threads ready run time so. @ worst, you'll slow things down bit.

the 1 thing want mindful of, such loop tie thread running it, making thread unavailable other stuff. don't want on ui thread, example. (there's application.doevents(), have call every on own, , use sign you're doing belongs in own thread.)


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -