c# - 为找到的每个项目更新进度条
问题描述
我的进度条和循环(在 C# 上)有问题。我需要解析一组项目(通过foreach循环),并且对于找到的每个对象,我需要增加一个进度条(通过for循环)......但是我的代码为找到的每个对象运行,这是正常的,但我找不到解决方法...
这是我的简化代码:
int totalSteps = lv_selection.Items.Count;
foreach (string p in lv_selection.Items)
{
for (int i = 0; i < totalSteps; i++)
{
// A time consuming job
(sender as BackgroundWorker).ReportProgress((int)(100 / totalSteps) * i, null);
// Update the progressbar's text (located in another form)
this.Dispatcher.Invoke(() =>
{
progressbarForm.Progress(p);
});
}
}
进度条按预期进行,但对于我的集合中的每个项目(“p”变量)。我明白为什么,但我不知道如何解决这个问题。
还尝试交换 for 和 foreach 循环。并在“耗时的工作”之后设置 for 循环。
有人可以帮助我吗?
非常感谢。
解决方案
我终于明白了!:)
我尝试使用一个技巧,并且效果很好。
我在 foreach 之前创建了一个整数变量,设置为 0。在 foreach 内部,我将此变量加一,并将其值作为一个步骤发送到我的进度条。
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
int totalSteps = lv_selection.Items.Count;
int currentStep = 0;
// Installations
foreach (string p in lv_selection.Items)
{
currentStep++;
// My long task
this.Dispatcher.Invoke(() =>
{
progressbarForm.Progress(p);
});
(sender as BackgroundWorker).ReportProgress((int)(100 / totalSteps) * currentStep, null);
}
}
推荐阅读
- javascript - 优化画布画圆
- javascript - 将鼠标悬停在图像上时,如何获得简单的灯箱以显示缩放效果
- c# - 使用 google oauth 授权 asp.net core web api(实体框架核心)
- garbage-collection - 为什么需要垃圾收集?
- python - 在 Windows/Linux 上使用 python3 脚本检查可执行文件是 32 位还是 64 位
- python - pandas:我怎样才能得到我想要的行的数据?
- javafx - JavaFX:阶段为空
- scala - 更改 Rw Spark scala 的 getValuesMap
- symfony - LiipImagine 过滤器在部署的 symfony 5 站点上不起作用
- c - 如何从文本文件中读取像“10:55”这样的时间,以便我们可以用 C 编程语言进行计算?