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

csharp 复制代码
private BackgroundWorker backgroundWorker;
private void UserControlCodeOperation_Load(object sender, EventArgs e)
{
    initialization();//初始化
    checkBoxOperation.Enabled = false;
    checkBoxCommand.Enabled = false;
    // 初始化 BackgroundWorker
    backgroundWorker = 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);
    }
}
csharp 复制代码
        #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
相关推荐
nbsaas-boot11 分钟前
Go语言生态成熟度分析:为何Go还无法像Java那样实现注解式框架?
java·开发语言·golang
xiaocainiao88121 分钟前
Python 实战:构建可扩展的命令行插件引擎
开发语言·python
碧海蓝天202244 分钟前
C++法则21:避免将#include放在命名空间内部。
开发语言·c++
兮动人1 小时前
Java应用全链路故障排查实战指南:从系统资源到JVM深度诊断
java·开发语言·jvm
bianguanyue1 小时前
SQLite密码修改故障排查:RSA加密随机性导致的数据库匹配问题
数据库·sqlite·c#
R-sz1 小时前
导出word并且插入图片
开发语言·c#·word
CodeWithMe1 小时前
【读书笔记】《C++ Software Design》第一章《The Art of Software Design》
开发语言·c++
脑袋大大的1 小时前
判断当前是否为钉钉环境
开发语言·前端·javascript·钉钉·企业应用开发
Wy. Lsy2 小时前
Kotlin基础学习记录
开发语言·学习·kotlin
Tanecious.2 小时前
C++--红黑树
开发语言·c++