我正在尝试编写一个简单的程序 (c#) 来读取一组 zip 文件以搜索某些特定文件。
我使用 winform 和后台工作程序实现了这个,但我在理解如何配置进度条以根据我正在解析的文件数量动态前进时遇到了一些麻烦。
例如,在目录 A 中,我有 400 个 zip 文件,所以我希望进度条的“大小”为 400 个单位,这样每个打开的文件都会使进度条增加 1。在目录 B 中,我只有 4 个 zip 文件所以我需要进度条中的 4 个 block
我尝试执行以下代码只是为了测试进度条 我将最大值设置为 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)问题解决了
最佳答案
Step
属性用于调用 PerformStep方法。
要设置进度条的当前位置,您可以使用 Increment
函数,如下所示:
progressBar.Increment(1);
或者像这样设置它的值:
progressBar.Value = yourValue;
关于c# - 进度条未根据最大尺寸前进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42386622/