【发布时间】:2017-07-12 05:09:40
【问题描述】:
我正在尝试编写一个简单的程序 (c#),它读取一组 zip 文件以搜索某些特定文件。
我使用 winform 和后台工作人员实现了这一点,但我在理解如何配置进度条以根据我正在解析的文件数量动态进行时遇到了一些麻烦。
例如,在目录 A 中,我有 400 个 zip 文件,所以我希望进度条的“大小”为 400 个单位,因此打开的每个文件都会将进度条增加 1。在目录 B 中,我只有 4 个 zip 文件所以我在进度条中需要 4 个块
我尝试执行以下代码只是为了测试进度条 我将最大值设置为 20(表示 20 个 zip 文件),并在循环中以 1 递增进度条
private void button_SearchZip_Click(object sender, EventArgs e)
{
if(!backgroundWorker_SearchZip.IsBusy)
{
SearchZipArgs args = new SearchZipArgs
{
sourceDirectory = this.textBox_SrcDir.Text
};
backgroundWorker_SearchZip.RunWorkerAsync(args);
this.button_SearchZip.Enabled = false;
}
else
{
MessageBox.Show(@"Search already in process. please try again later");
}
}
private void backgroundWorker_SearchZip_DoWork(object sender, DoWorkEventArgs e)
{
this.progressBar_SearchZip.Style = ProgressBarStyle.Blocks;
//this.progressBar_SearchZip.Step = 1;
this.progressBar_SearchZip.Minimum = 0;
this.progressBar_SearchZip.Maximum = 20;
for(int i = 0; i < 20; i++)
{
backgroundWorker_SearchZip.ReportProgress(i);
Thread.Sleep(300);
}
}
public MainForm()
{
InitializeComponent();
this.backgroundWorker_SearchZip.WorkerReportsProgress = true;
this.backgroundWorker_SearchZip.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker_SearchZip_DoWork);
this.backgroundWorker_SearchZip.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker_SearchZip_ProgressChanged);
this.backgroundWorker_SearchZip.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.backgroundWorker_SearchZip_RunWorkerCompleted);
}
private void backgroundWorker_SearchZip_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar_SearchZip.Value = e.ProgressPercentage;
}
但这是我在进度条中得到的:
由于某种原因,如果取消注释:
this.progressBar_SearchZip.Step = 1;
进度条根本不工作
任何帮助都会很好:)
编辑: 发现问题了!我试图从后台线程更改进度条,但出现错误“跨线程操作无效:控制'progressBar Search Zip'从创建它的线程以外的线程访问” 修复此错误后(在此线程的帮助下:Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on)问题解决了
【问题讨论】:
-
backgroundWorker.ProgressChanged 事件在哪里?
-
@A3006 忘记添加了。我已经编辑了问题
标签: c# winforms progress-bar