可能重复:
Updating a Progress Bar from Another Thread更新在C#GUI一个进度条,从另一个线程和类
在我的计划,我想非GUI功能分离到另一个类,并在主类中留下与GUI相关的东西。但是,在工作者类中的其中一个工作方法正在完成其工作时,我遇到了更新进度条的问题。我知道我必须在这里使用多线程,但我不知道如何。我可能会错过简单的东西,但是当我查找有关它的信息时,似乎大多数教程都谈论细节,但不能很好地解释大局。我部分理解了调用和委托命令是什么,但我并不真正了解它们如何交互。
下面是我想要做的事情的简化版本。我如何修改这个来更新进度条,但保持窗口响应并重新绘制?
主要形式类:
public partial class Form1 : Form
{
time_waster thing = new time_waster();
public Form1()
{
InitializeComponent();
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
}
private void button1_Click(object sender, EventArgs e)
{
thing.something_that_takes_a_while();
}
}
单独的工作类: 类time_waster { 公共time_waster() { }
public void something_that_takes_a_while()
{
int delay = 200;
for (int i = 0; i < 100; i++)
{
Thread.Sleep(delay);
//appropriate code to update the progress bar for each iteration of the for loop.
}
}
}
使用委托和调用方法来更新UI上的控件。 –