计时器停止时调用BackgroundWorker RunWorkerCompleted事件

时间:2012-01-30 11:40:27

标签: c# timer backgroundworker

我有BackgroundWorker创建计时器。计时器重复调用DataTable。我只希望在计时器停止时调用BackgroundWorker.RunWorkerCompleted事件。我该怎么做?

感谢。

2 个答案:

答案 0 :(得分:2)

只需在BackgroundWorker的{​​{1}}事件处理程序中创建一个循环,然后重复循环直到计时器停止。或多或少如此:

DoWork

(显然我省略了设置计时器的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 }; 等)

答案 1 :(得分:1)

在DoWork事件完成后调用BackGroundWorker.RunWorkerCompleted。因此,如果您确保DoWork事件完成,则应由后台工作程序调用RunWorkerCompleted事件。

另一种解决方案是在后台工作程序之外创建计时器,并从计时器控制后台工作程序实例。在timer事件中,检查IsBusy属性是否设置为false并启动后台工作程序或如果IsBusy为true则跳过。

样品:

_worker.DoWork += (sender, e) =>
{   
    BackgroundWorker worker = sender as BackgroundWorker;

    // Do your database stuff

    e.Result = databaseResult;
}

_timer.Elapsed += (source, e) =>
{
    if(!_worker.IsBusy)
    {
        _worker.RunWorkerAsync();
    }
}