c# - Backgroundworker and CPU usage -


i need background work every 20 seconds (it doesn't have 20000ms, can allow delays). using backgroundworker executes function , wait 20 seconds using timer:

private readonly backgroundworker worker = new backgroundworker(); volatile bool keepworkerrunning;  worker.dowork += worker_dowork;       private void worker_dowork(object sender, doworkeventargs e)     {         system.timers.timer atimer = new system.timers.timer();         atimer.elapsed += new elapsedeventhandler(ontimedevent);         atimer.interval = 20000;         atimer.enabled = true;         keepworkerrunning = true;         while (keepworkerrunning) ;         atimer.enabled = false;     } 

this worker active whole time while software running.

the problem takes of cpu. noticed software using around 70% of cpu time, , deactivating backgroundworker cpu usage drops 0.5%.

how can same job without overloading cpu?

the cpu eaten loop:

while (keepworkerrunning); 

you instruct cpu loop "doing nothing" fast possible. hence 70% cpu load, might worse (up 100% depending on cpu/cores).

don't use backgroundworker @ all. elapsed event raised timer on thread pool thread (the synchronizingobject property of timer should null), run in background.

more information can here.


update: requested, here sample.

using system.timers;  class myclass : idisposable {   readonly timer atimer = new timer(20000);    public void starttimer()   {     this.atimer.elapsed += this.ontimedevent;     this.atimer.enabled = true;   }    void ontimedevent(object source, elapsedeventargs e)   {     // background work here   } } 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -