简体   繁体   English

查找文件时的ProgressBar

[英]ProgressBar while finding a file

Hi I am trying to show a progress bar while in background the code is looping till it finds a file with specific name. 嗨,我正在尝试显示一个进度条,而在后台,代码不断循环直到找到具有特定名称的文件。

I have written following code for that but the progress bar values doesn't change. 我为此编写了以下代码,但是进度栏的值没有改变。

What should I change in the code below? 我应该在下面的代码中进行哪些更改?

public partial class Form1 : Form
{
    BackgroundWorker backgroundWorker1 = new BackgroundWorker();  
    public Form1()
    {
        InitializeComponent();
        progressBar1.Visible = false;
        backgroundWorker1.WorkerReportsProgress = true;

        backgroundWorker1.DoWork +=
            new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.ProgressChanged +=
            new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        backgroundWorker1.RunWorkerCompleted +=
            new RunWorkerCompletedEventHandler(backgroundWorker1_WorkDone);

    }

    private void button1_Click(object sender, EventArgs e)
    {
        backgroundWorker1.RunWorkerAsync();
        progressBar1.Visible = true;
    }

    void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        // Your background task goes here
        for (int i = 0; i <= 100; i++)
        {
            // Report progress to 'UI' thread
            backgroundWorker1.ReportProgress(i);
            // Simulate long task


            while (!File.Exists(@"C:\Users\Test.txt"))
            {
                continue;
            }
        }
    }

    void backgroundWorker1_ProgressChanged(object sender,
        ProgressChangedEventArgs e)
    {
        // The progress percentage is a property of e
        progressBar1.Value = e.ProgressPercentage;
    }

    void backgroundWorker1_WorkDone(object sender,
        RunWorkerCompletedEventArgs e)
    {
        progressBar1.Visible = false;
    }
}

The continue in your code will simply continue to the next iteration of the while(true) loop. 代码中的continue将继续到while(true)循环的下一个迭代。 It won't go back up to the for loop as you expect - it just keeps looping in there over and over again. 它不会像您期望的那样返回到for循环-它只会不断地在其中循环。 If it wasn't a background worker, it'd hang your entire program. 如果不是背景工作者,它将挂起您的整个程序。 Since it is, it just hangs that thread. 既然如此,它只会挂起该线程。 I expect that one CPU core stays at 100% while this is running. 我希望在运行时一个CPU核心保持在100%。

That being said, while the goal here is admirable, there's no good way to accomplish it. 话虽这么说,尽管这里的目标令人钦佩,但没有实现它的好方法。 Even if you fix the infinite loop, your progress bar will either "finish" at a low percentage (1%, 2%, 3%, done) or go up to 100, then stop updating, but without the file yet existing. 即使修复了无限循环,进度条也会以较低的百分比(完成1%,2%,3%)“完成”,或者达到100,然后停止更新,但是文件不存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM