我有一个 Windows 窗体,它是一个模态 mdi 子窗体,假设在一些密集的后台工作正在进行时显示,因此用户在该工作完成之前不能使用任何控件。
很简单,下面是代码。
public partial class ProgressForm : Form
{
private int periodCount = 5;
public ProgressForm(String message)
{
InitializeComponent();
messageLabel.Text = message;
}
public void startThread()
{
Thread t = new Thread(new ThreadStart(doWork));
t.IsBackground = true;
t.Start();
}
void doWork()
{
while (true)
{
if (periodCount == 5)
{
periodCount = 1;
}
else
{
periodCount++;
}
switch (periodCount)
{
case 1: periodsLabel.Text = "."; break;
case 2: periodsLabel.Text = ". ."; break;
case 3: periodsLabel.Text = ". . ."; break;
case 4: periodsLabel.Text = ". . . ."; break;
case 5: periodsLabel.Text = ". . . . ."; break;
}
}
}
}
但是,periodsLabel.Text 并没有像预期的那样改变!如何在后台执行其他操作时更新 UI?
ProgressForm progressForm = new ProgressForm("Your database data is being exported, please wait.");
progressForm.ShowDialog();
progressForm.startThread();