c#using backgroundworker我希望在保存数据库时获得“时间过程”

时间:2013-06-17 03:49:14

标签: c# backgroundworker

    private void btnUpdate_Click(object sender, EventArgs e)
    {                 
      bgWorker.RunWorkerAsync();                                
    }

    private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
    {          
        BackUpDatabase.BackUp(this.txtPath.Text);
        for (int i = 0; i <= 100; i++)
        {
            // Report progress to 'UI' thread
            bgWorker.ReportProgress(i);
            // Simulate long task
            System.Threading.Thread.Sleep(100);
        }
    }

    private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
        lblProgress.Text = String.Format("Progress: {0} %", e.ProgressPercentage);
    }

代码正在运行,但我怀疑进度不是确切的时间过程。我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:0)

你的问题有点模糊,不过不好给它一个裂缝:

听起来我需要两个后台工作人员,一个用于实际备份,另一个用于实时报告时间。

幸运的是,有一个在后台线程中运行的计时器! System.Timers.Timer。

您已经有一个线程设置来完成工作,所以您只需创建计时器,然后启动/更新/停止它。

下面是代码如何工作:

private Timer _Timer;
private DateTime _Start;
private void InitTimer()
{
    _Start = DateTime.Now;
    _Timer = new Timer(100);
    _Timer.AutoReset = false;
    _Timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
    _Timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs  e)
{
    TimeSpan diff = DateTime.Now - _Start;
    this.Invoke(new MethodInvoker(delegate()
    {
        lblProgress.Text = String.Format("Time: {0}", diff);
    }));
}
//starts the worker thread
private void btnUpdate_Click(object sender, EventArgs e)
{
    InitTimer();
    bgWorker.RunWorkerAsync();
}
//Does the backup
private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    BackUpDatabase.BackUp(this.txtPath.Text);
}
//Stops the timer when the backup finishes
private void bgWorker_WorkCompleted(object sender, RunWorkerCompletedEventArgs e)
{

    _Timer.Stop();
}

我还没有测试过这段代码,我可能会以此为基础:)但请尽情享受:)

编辑:

考虑一下这个问题,如果OP希望获得百分比,他需要将备份分解为步骤并手动报告。