我正在尝试编写一个简单的程序(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搜索Zip'访问从其创建的线程以外的线程” 修复此错误后(在此主题的帮助下:Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on)问题解决了
答案 0 :(得分:1)
Step
属性用于调用PerformStep方法。
要设置进度条的当前位置,您可以使用Increment
功能,如下所示:
progressBar.Increment(1);
或设置其值如下:
progressBar.Value = yourValue;
答案 1 :(得分:1)
您需要添加
backgroundWorker_SearchZip.ProgressChanged += this.OnProgressChanged;
进入初始化函数(例如Form_Load
)
然后添加
private void OnProgressChanged(object sender, ProgressChangedEventArgs e) {
this.progressBar_SearchZip.Increment(1);
}
答案 2 :(得分:0)
此代码适用于我:
this.progress_bar.Properties.Minimum = 0;
this.progress_bar.Properties.Maximum = datatable.Rows.Count;
foreach (DataRow row in datatable.Rows) {
// operation that you need to do
this.progress_bar.Increment(1);
this.progress_bar.Update();
}
祝你好运
答案 3 :(得分:0)
我试图从后台线程更改进度条,我收到错误“跨线程操作无效:控制'progressBar搜索Zip'从其创建的线程以外的线程访问”
修复此错误后(在此主题的帮助下:Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on)问题解决了