c# - 为什么 ProgressBar 不显示当前值/不刷新?
问题描述
我使用以下代码:
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 时,进度条还有更多的步骤要完成。
我做错了什么?
为什么进度条的值没有更新?
我应该怎么做正确?
解决方案
你在使用任务、异步、等待吗?这是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));
}
推荐阅读
- elasticsearch - 如何在 Kubernetes 状态集中恢复永久磁盘?
- c# - 我想在 asp.net 中向 gridview 添加垂直滚动条
- sql-server - 同一业务规则的多个外键
- highcharts - Highcharts 地图在调用 setData 时未绘制气泡
- javascript - 如何将输入数据与跨度文本绑定?
- python - 如何在 Python 中重塑这个 DataFrame?
- python - 将分类模型用于对象检测框架
- python - for 循环的问题 - Pandas
- reactjs - 服务器端渲染 - 在 css 包之间切换
- javascript - 转换旋转的 Firefox 抽搐问题