【问题标题】:Update progressbar for each item found为找到的每个项目更新进度条
【发布时间】:2018-10-25 08:31:07
【问题描述】:

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

有人可以帮帮我吗?

非常感谢。

【问题讨论】:

  • 如果“进度条按预期进行”,那么您的问题是什么?我不明白你在问什么
  • 究竟什么是“进度条”?这是什么技术? MVC、WPF、Winforms、Xamarin??!
  • 抱歉,我可能解释错了 :) 我的意思是进度条填充正确,但它会为找到的每个项目重新开始。如果我的收藏中有 4 个项目,进度条将填充 4 次。它是一个 WPF ProgressBar,在 c# 代码中管理。

标签: c# loops for-loop foreach


【解决方案1】:

我终于明白了! :)

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

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

            }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-20
    • 2013-11-10
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2013-03-08
    相关资源
    最近更新 更多