c# - Correct way to prevent high CPU usage with infinite while loop (Console/Forms hybrid) -


i put console/forms hybrid program, , achieve behavior looking had "run" console in thread, , launch dashboard another.

i used backgroundworker this. in main method start console background worker in dowork block performs normal while loop keep console going. repetitively checking input console , passing along corresponding action.

while (true && !program.shutdown) {     string consoleinput = "";      consoleinput = program.readfromconsole();      if (string.isnullorwhitespace(consoleinput))         continue;      try     {         program.shell(consoleinput);     }     catch (exception ex)     {         program.writetoconsole(ex.message);     } } 

after background worker starting console called i.e. consolebackgroundworker.runworkerasync() call method performs loading sequence.

this loading sequence can call second background worker internally launches dashboard on separate thread.

now problem faced loop @ end of load sequence. loop prevents shutting down until both of background workers have completed (the forms closed or console sent command shutdown)

while (consolebackgroundworker != null && dashboardbackgroundworker != null) {     /* i'm not sure of how else fix this.       * corrects high cpu usage reported       * in task manager. */     system.threading.thread.sleep(10); } 

the problem cpu usage, sitting @ 30% , without line see above system.threading.thread.sleep(10)

my question is, ok? , if not solution have? noticed did correct issue, cpu rides @ 0% when application not doing anything. haven't seen performance changes either. has not been "pushed" yet couldn't sure on latter observation.

instead of polling (checking every 10ms, you've done) "better" (or @ least less cpu intensive) solution use kind of wait-functions. use manualresetevent maybe, or of other synchronization objects available in system.threading namespace. depends on need. can call .wait() on object , block thread (0% actual cpu usage) until kind of signal arrives thread.


Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -