您好我正在尝试在后台显示进度条,代码正在循环,直到找到具有特定名称的文件。
我已为此编写了以下代码,但进度条值不会更改。
我应该在下面的代码中更改什么?
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;
}
}
答案 0 :(得分:1)
代码中的continue
将继续执行while(true)
循环的下一次迭代。它不会像你期望的那样回到for
循环 - 它只是一遍又一遍地在那里循环。如果它不是后台工作者,它会挂起整个程序。既然如此,它只是挂起那个线程。我希望在运行时,一个CPU核心保持在100%。
话虽如此,虽然这里的目标令人钦佩,但没有好办法实现它。即使您修复了无限循环,您的进度条也会以低百分比(1%,2%,3%,完成)“完成”或最多100,然后停止更新,但文件尚未存在。< / p>