【问题标题】:How to use ProgressBar inside nested foreach loop?如何在嵌套的 foreach 循环中使用 ProgressBar?
【发布时间】:2013-11-08 07:27:49
【问题描述】:

如何在嵌套的 foreach 循环中正确使用进度条? 因为我是这样做的,而我在 foreach 循环进程中的进程只执行到我正在比较的第二个文件。

int count = d1.GetFiles(fd.fileType, SearchOption.AllDirectories).Length;
int current = 0;
foreach(...)
{
    foreach(...)
    {
      //process
    }
current++;
pbSearch.Value = current / count * 30 + 70;
label1.Text = pbSearch.Value.ToString();
}

【问题讨论】:

  • went crazy你说的很慢,不是吗?
  • 您需要为您的问题提供比“发疯”更准确的详细信息,否则 stackoverflow.com 中的人也会发疯 :-)
  • 我认为进度条必须附加一个线程来更新进度条,这是正确的方法。为什么要在嵌套循环中更新进度条?请解释
  • 我需要一个进度条,因为我要比较的文件太多。
  • 使用指示文件进度的变量(复制删除等)作为线程函数的参数,并根据这些参数更新进度条

标签: c# foreach progress-bar nested-loops


【解决方案1】:

根据你的两个foreach循环你可以考虑使用两个进度条或者重新计算最大值,看看这个MSDN例子:

    private void CopyWithProgress(string[] filenames)
    {
        // Display the ProgressBar control.
        pBar1.Visible = true;
        // Set Minimum to 1 to represent the first file being copied.
        pBar1.Minimum = 1;
        // Set Maximum to the total number of files to copy.
        pBar1.Maximum = filenames.Length;
        // Set the initial value of the ProgressBar.
        pBar1.Value = 1;
        // Set the Step property to a value of 1 to represent each file being copied.
        pBar1.Step = 1;

        // Loop through all files to copy. 
        for (int x = 1; x <= filenames.Length; x++)
        {
            // Copy the file and increment the ProgressBar if successful. 
            if(CopyFile(filenames[x-1]) == true)
            {
                // Perform the increment on the ProgressBar.
                pBar1.PerformStep();
            }
        }
    }

【讨论】:

  • 谢谢!这很有帮助。但由于我有数千个文件,所以我的工具滞后......就像显示正在比较的文件名的工具条没有更新。虽然当我显示一个消息框时,它正在更新......
  • 你可以调用Application.DoEvents();在您的循环中,以便更新进度条msdn.microsoft.com/en-us/library/…
  • 请注意文档中的警告部分:调用此方法会导致当前线程暂停,同时处理所有等待窗口消息。如果消息导致事件被触发,那么您的应用程序代码的其他区域可能会执行。这可能会导致您的应用程序出现难以调试的意外行为。
猜你喜欢
  • 2015-07-15
  • 1970-01-01
  • 1970-01-01
  • 2020-06-07
  • 2012-05-16
  • 2015-07-06
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
相关资源
最近更新 更多