0
    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);
    }

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

4

1 回答 1

0

你的问题有点含糊,但我还是给它一个破解:

在我看来,您需要两名后台工作人员,一名负责实际备份,一名负责实时报告时间。

幸运的是,有一个在后台线程中运行的计时器!系统.定时器.定时器。

您已经设置了一个线程来完成这项工作,因此您所要做的就是创建您的计时器,然后启动/更新/停止它。

下面是代码的工作方式:

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 想要获得一个百分比,他将需要将他的备份分解为步骤并手动报告。

于 2013-06-17T05:20:42.170 回答