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
相关推荐
一点媛艺1 小时前
Kotlin函数由易到难
开发语言·python·kotlin
姑苏风1 小时前
《Kotlin实战》-附录
android·开发语言·kotlin
奋斗的小花生2 小时前
c++ 多态性
开发语言·c++
魔道不误砍柴功2 小时前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python
闲晨2 小时前
C++ 继承:代码传承的魔法棒,开启奇幻编程之旅
java·c语言·开发语言·c++·经验分享
老猿讲编程2 小时前
一个例子来说明Ada语言的实时性支持
开发语言·ada
Chrikk3 小时前
Go-性能调优实战案例
开发语言·后端·golang
幼儿园老大*3 小时前
Go的环境搭建以及GoLand安装教程
开发语言·经验分享·后端·golang·go
canyuemanyue3 小时前
go语言连续监控事件并回调处理
开发语言·后端·golang
杜杜的man3 小时前
【go从零单排】go语言中的指针
开发语言·后端·golang