首页 > 解决方案 > 为找到的每个项目更新进度条

问题描述

我的进度条和循环(在 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 循环。

有人可以帮助我吗?

非常感谢。

标签: c#loopsfor-loopforeach

解决方案


我终于明白了!:)

我尝试使用一个技巧,并且效果很好。

我在 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);

            }
    }

推荐阅读