I need to do some background work every 20 seconds (it doesn't have to be exactly 20000ms, I can allow delays). I am using a Backgroundworker that executes the function and then wait another 20 seconds using a 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 is active for the whole time while the software is running.
The problem is that it takes most of the CPU. I noticed that my software is using around 70% of the CPU all the time, and just deactivating the Backgroundworker the CPU usage drops to 0.5%.
How can I do the same job without overloading the CPU?