Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backgroundworker Sleep to reduce CPU

I have a task that i want to run over and over. I want to call this as fast as possible however i want to keep my cpu cycles low. I have read using Sleep in a backgroundworker is not the best choice. However without sleep my cpu stays about 55% percent. I have an example of my source below. If sleep is appropriate how do you go about choosing the best time to sleep, as you can see from my results below i get different results based on how long i sleep. Can someone let me know what best practice is when doing something similar

BackgroundWorker _Worker = new BackgroundWorker()
{
  WorkerReportsProgress = true,
  WorkerSupportsCancellation = true
};

void Worker_DoWork(object sender, DoWorkEventArgs e)
{
    // do my task here

    // if i uncomment one of the Sleep below I reduce the CPU like so
    // no sleep             CPU = 52-58%
    // Thread.Sleep(1);     CPU = 09-15%
    // Thread.Sleep(10);    CPU = 02-03%
    // Thread.Sleep(100);   CPU = 00-01%
}

void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled) { return; }

    _Worker.RunWorkerAsync();
}
like image 211
poco Avatar asked Nov 04 '22 10:11

poco


1 Answers

With multi-threading, it's common to set background work to a lower priority when you don't want to consume the machine. It will use whatever CPU is left over. That means you shouldn't care if it goes to 100%.

But, the problem with BackgroundWorker is you can't set the priority.

Another option is to spawn your own thread which you can set the priority on.

Here's another related SO post:

.NET Backgroundworker Object's Thread Priority

Also, another (likely less attracted) option is to put the heavy work into another process and make that run low priority. If you don't need to communicate alot of progress, it's simple. Otherwise it's more complex to open a communication channel.

How do I launch a process with low priority? C#

like image 181
bryanmac Avatar answered Nov 11 '22 18:11

bryanmac