我想在我的程序运行某些功能时显示进度条。当用户单击 button1 时,此函数正在运行。我使用了在后台运行的 tread,但在我的程序中,这个线程在程序运行完这个函数后运行。我该如何修复它?
private void button1_Click(object sender, EventArgs e)
{
pr(sender,e);
}
public void pr(object sender, EventArgs e)
{
if (... == DialogResult.OK)
{
if (...)
{
Thread wa = new Thread(new ThreadStart(this.lad));
wa.IsBackground = true;
timer1.Interval = 500;
timer1.Start();
wa.Start();
if (... == DialogResult.OK)
{//the rest of the function}
}
}
}
private void lad()
{
int war = 10;
if (this.progressBar1.InvokeRequired)
{
progressBar1.Invoke((Del)delegate
{
for (int i = 1; i <=10; i++)
{
this.progressBar1.Value = this.progressBar1.Value + war;
}
});
}
if (progressBar1.Value == progressBar1.Maximum)
{
timer1.Stop();
MessageBox.Show("files saved");
}
}
private void timer1_Tick(object sender, EventArgs e)
{
ladowanie_paska();
}
最佳答案
我强烈建议重写代码以使用 BackgroundWorker 类;
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
这将使使用 ProgressChanged 事件更新用户界面变得更加容易
关于c# - 后台 C# 中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4549181/