进度条查询-最大值不同

本文关键字:最大值 查询 | 更新日期: 2023-09-27 18:23:52

我有一个读取文件头的应用程序,我想实现一个进度条,但我在尝试基于这个Microsoft示例使其工作时遇到了问题。

该示例处理复制的文件。

我希望条形图能处理每个文件,下面是我的代码,它所做的就是在读取所有文件后达到最大值。我打开以读取文件头的文件夹可以有1个文件或1000个文件。

我对这一点感到困惑,加上我可能把代码放错了地方。。。

if (CopyFile(files[x-1]) == true)

我也不认为我的线程工作得很好,所以给我一些建议也很好。

private void btnOpenFile_Click(object sender, EventArgs e)
    {
        DialogResult result = folderBrowserDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            ThreadStart t = delegate {};
            listBoxResults.Items.Clear();
            string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
            txtFilesFound.Text = files.Length.ToString();
            {
                string path = folderBrowserDialog1.SelectedPath;
                foreach (string filepath in Directory.GetFiles(path, comboFileType.Text, SearchOption.TopDirectoryOnly))
                {
                    foreach (string item in GetHeaderInformation(filepath))
                    {
                        this.Invoke(new Action(() => txtUpdate(item)));
                        // 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 read.
                        pBar1.Maximum = files.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 read.
                        pBar1.Step = 1;
                    }
                    this.Invoke(new Action(() => txtUpdate(filepath + Environment.NewLine)));
                    this.Invoke(new Action(() => txtUpdate("***************************************************************************")));
                    for (int x = 1; x <= files.Length; x++)
                       //if(CopyFile(files[x-1]) == true)
                            //{
                            // Perform the increment on the ProgressBar.
                                pBar1.PerformStep();
                            //}
                }
            };
            new Thread(t).Start();
        }
    }

如有任何帮助,我们将不胜感激。

也许这个例子可能更有益。

进度条查询-最大值不同

进度条在UI线程上运行。更新进度条后,UI线程必须从代码中返回并继续处理窗口消息,以便重新绘制窗口。

如果代码在繁忙循环中运行,则在循环完成并将控制权返回到主应用程序循环之前,无法处理任何进度更新。因此,在启动线程后,您需要确保事件处理程序返回控制,而不是坐着等待或做其他工作。

您需要在计时器上使用定期更新,或者(更好)在后台线程中运行处理,并定期将进度更新传递回UI线程。然而,如果您只是从另一个线程中插入ui控件,您将得到一个跨线程的person和未定义的结果。

大多数进度条示例应该向您展示如何使用BackgroundWorker或类似工具来完成后者。