您的位置:首页 > 健康 > 养生 > C# BackgroundWorker_DoWork和进度条progressBar1 绑定,逐行处理耗时任务

C# BackgroundWorker_DoWork和进度条progressBar1 绑定,逐行处理耗时任务

2024/12/28 11:35:17 来源:https://blog.csdn.net/lizhihua0625/article/details/140841323  浏览:    关键词:C# BackgroundWorker_DoWork和进度条progressBar1 绑定,逐行处理耗时任务
private BackgroundWorker backgroundWorker;
private void UserControlCodeOperation_Load(object sender, EventArgs e)
{initialization();//初始化checkBoxOperation.Enabled = false;checkBoxCommand.Enabled = false;// 初始化 BackgroundWorkerbackgroundWorker = new BackgroundWorker{WorkerReportsProgress = true,WorkerSupportsCancellation = true};backgroundWorker.DoWork += BackgroundWorker_DoWork;backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;}
int count = 100;
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{if (codeLines.Count > 0){count = codeLines.Count;}// 模拟长时间操作for (int i = 0; i < count; i++){if (backgroundWorker.CancellationPending){e.Cancel = true;break;}// 更新进度backgroundWorker.ReportProgress(i, codeLines[i]);//System.Threading.Thread.Sleep(10); // 模拟操作时间}
}private void StartBackgroundWork()
{// 显示进度条progressBar1.Visible = true;progressBar1.Value = 0;LoadImg.Left = this.Width / 2 - 38;LoadImg.Visible = true;string DateTimeNow = String.Format("{0} {1} {2}", DateTime.Now, "StartBackgroundWork", Environment.NewLine);// 获取项目所在路径string dirPath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);string fileName = String.Format("log_{0:yyyyMMdd}.log", DateTime.Now);string filePath = System.IO.Path.Combine(dirPath, "log", fileName);AnalysisCodeClass.CodeFile.WriteLog(filePath, DateTimeNow);// 启动后台工作if (!backgroundWorker.IsBusy){backgroundWorker.RunWorkerAsync();}
}private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{Console.Write(e.ProgressPercentage);Console.Write(e.UserState);// 更新进度条if (e.ProgressPercentage * 100 / count > 100){progressBar1.Value = 100;}else{progressBar1.Value = e.ProgressPercentage * 100 / count;}            string DateTimeNow = String.Format("{0} {1} {2}", DateTime.Now, "", Environment.NewLine);Console.Write(DateTimeNow);// 执行操作ClassCodeStruct.CodeLine codeLine = (ClassCodeStruct.CodeLine)e.UserState;Console.Write(codeLine.Code);// 逐行处理,并渲染到界面DisplayCodeLines(codeLine, e.ProgressPercentage);
}private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{// 隐藏进度条progressBar1.Visible = false;if (e.Cancelled){progressBar1.Visible = false;MessageBox.Show("取消成功");}else if (e.Error != null){MessageBox.Show("执行出错 " + e.Error);}else{var res = e.Result;progressBar1.Value = 100;progressBar1.Visible = false;LoadImg.Visible = false;SetComboBox();//MessageBox.Show("操作完成 " + res);//MessageBox.Show("操作完成 " + DateTime.Now);string DateTimeNow = String.Format("{0} {1} {2}", DateTime.Now, "BackgroundWorker_RunWorkerCompleted", Environment.NewLine);// 获取项目所在路径string dirPath = System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);string fileName = String.Format("log_{0:yyyyMMdd}.log", DateTime.Now);string filePath = System.IO.Path.Combine(dirPath,"log", fileName);AnalysisCodeClass.CodeFile.WriteLog(filePath, DateTimeNow);}
}
        #region 写日志文件public static void WriteLog(string fileName, string text){//如果文件夹不存在,创建文件夹string path = Path.GetDirectoryName(fileName);if (!System.IO.Directory.Exists(path)){System.IO.Directory.CreateDirectory(path);}// 如果文件不存在则创建文件           //if (!System.IO.File.Exists(fileName))//{//    FileStream fs = System.IO.File.Create(fileName);//    fs.Close();//}//StreamWriter sw = new StreamWriter(fileName, true);//sw.WriteLine(text);//sw.Close();using (StreamWriter sw = new StreamWriter(fileName, true)){sw.WriteLine(text);}}#endregion

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com