关于C#进度条
假设我有十个文件需要去分析,当传递给我一个消息告诉我要开始分析的时候,我需要刷新一下进度条,当完成一个文件的分析时进度条完成1/10...当十个文件都完成时又会传递给我一个完成的消息,进度条完成100%,如何用一个方法来实现,求大神帮忙,在线等待。。。 C# 进度条
[解决办法]
使用backgroundworker会方便很多,拖一个backgroundworker到界面和一个进度条,按钮点击开始处理文件
void startOpFile()
{
if(backgroundworker.isbusy) return;
backgroundWorker.RunWorkerAsync(你的文件个数);
}
//backgroundworker的事件都要用上
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
KeyValuePair<int,string> record = (KeyValuePair<int,string>) e.UserState ;
label.Text = string.Format("{0}", record.Key+"="+(((double)record.Key / (double)你文件的个数)).ToString("P3"));
label.Update();
progressBarLeft.Value = e.ProgressPercentage;//进度条
progressBarLeft.Update();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
e.Result = this.RetrieveData(this.backgroundWorker, e);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
try
{
label.Text = string.Format("总记录: {0}", e.Result);
}
catch (TargetInvocationException ex)
{
MessageBox.Show(ex.InnerException.GetType().ToString());
}
}
//主要是写这么一个方法返回处理的值
private int RetrieveData(BackgroundWorker worker, DoWorkEventArgs e)
{
int maxRecords = (int)e.Argument;
int percent = 0;
Application.DoEvents();//
for (int i = 1; i <= maxRecords; i++)
{
if (worker.CancellationPending)
{
return i;
}
percent = (int)(((double)i / (double)maxRecords) * 100);
worker.ReportProgress(percent, new KeyValuePair<int,string>(i,Guid.NewGuid().ToString()));
Thread.Sleep(1000);//模拟测试
}
return maxRecords;
}
大概思路是这样子,LZ你再去摸索下就更加深刻了。
哦对了,再加一个是马上终止当前处理的:
void stopOp()
{
backgroundWorker.CancelAsync();
}