我创建了一个表单,每当我调用一个耗时的例程时,它就会弹出并显示一个进度条。UpdateProgress
我通过该方法提供了我日常工作的进度。
我正在使用后台工作人员来允许用户移动表单并在此表单更新时继续开展业务。但是,表单会一直锁定,直到例程完成,然后快速将进度条增加到 100% 并退出(应该如此)。imo,进度条应该与对该UpdateProgress
方法的调用进度一起更新。
我在这里做错了什么?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace myNameSpace
{
public partial class ProgressIndicator : Form
{
int progressPercentage;
public ProgressIndicator()
{
InitializeComponent();
}
void progressUpdater_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// update the UI with appropriate fields
progressBar.Value = e.ProgressPercentage;
labelCommunicating.Text = "In progress: " + e.ProgressPercentage + "% complete";
}
void progressUpdater_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
void progressUpdater_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (true)
{
if (progressPercentage >= 100)
{
break;
}
worker.ReportProgress(progressPercentage);
Thread.Sleep(100);
}
}
public void UpdateProgress(int progressPercentage)
{
this.progressPercentage = progressPercentage;
}
private void ProgressIndicator_Load(object sender, EventArgs e)
{
BackgroundWorker progressUpdater = new BackgroundWorker();
progressUpdater.WorkerReportsProgress = true;
progressUpdater.WorkerSupportsCancellation = true;
progressUpdater.DoWork += new DoWorkEventHandler(progressUpdater_DoWork);
progressUpdater.RunWorkerCompleted += new RunWorkerCompletedEventHandler(progressUpdater_RunWorkerCompleted);
progressUpdater.ProgressChanged += new ProgressChangedEventHandler(progressUpdater_ProgressChanged);
progressUpdater.RunWorkerAsync();
}
}
}