Search code examples
c#timerbackgroundworker

Call BackgroundWorker RunWorkerCompleted event when timer stops


I have a BackgroundWorker that creates a timer. The timer makes repeated calls to a DataTable. I only want the BackgroundWorker.RunWorkerCompleted event to get called when the timer stops. How do I do this?

Thanks.


Solution

  • Just create a loop in the BackgroundWorker's DoWork event handler and repeat the loop until the timer stops. More or less like so:

    var worker = new BackgroundWorker();
    worker.DoWork += (sender, e) =>
    {
        var timer = new Timer();
        timer.Elapsed += (s, _e) =>
        {
           // call the database
        };
    
        timer.Start();
    
        while (timer.Enabled)
        {
            // at some point: timer.Stop();
        } 
    
        // if we are here, timer is no longer Enabled
        // RunWorkerCompleted event will be fired next
    };
    

    (Obviously I ommitted setting the timer's Interval etc.)