我使用以下代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
progressBar1.Value = 0;
progressBar1.Step = 1;
progressBar1.Maximum = 100;
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);
progressBar1.PerformStep();
label1.Text = (i + 1).ToString();
this.Refresh();
}
}
}
但是,即使在this.Refresh();
之后,进度条的值也不会更新。仅标签更新。当标签已经显示100时,对于进度条stil,还有更多步骤可以完成。
我做错了什么?
为什么进度条的值不更新?
我应该如何纠正?
答案 0 :(得分:0)
您是否正在使用Task,async,await?这是Winforms中的常见示例
public void DoWork(IProgress<int> progress)
{
// This method is executed in the context of
// another thread
for (int j = 0; j < 100000; j++)
{
//DO something
// Use progress to notify UI thread that progress has
// changed
if (progress != null)
progress.Report((j + 1) * 100 / 100000);
}
}
private async void button_Click(object sender, EventArgs e)
{
progressBar.Maximum = 100;
progressBar.Step = 1;
var progress = new Progress<int>(v =>
{
// This lambda is executed in context of UI thread,
// so it can safely update form controls
progressBar.Value = v;
});
// Run operation in another thread
await Task.Run(() => DoWork(progress));
}
答案 1 :(得分:0)
我尝试了您的代码,它对我来说很好用,您是否在进度栏中添加了任何特殊属性?
假设它已包含所有内容,请尝试将其删除并添加新的而不调整其默认属性,也可以尝试调整Thread.Sleep()
中的值,以便进一步查看进度< / p>