【C#】跨线程更新进度条_UpdateProgress 方法解析

文章目录

UpdateProgress 方法解析

下边是实战项目中的一段代码,比较有代表性,对其进行解析

csharp 复制代码
private void UpdateProgress(int current, int total, string message)
{
    // ===== Cross-thread Safety =====
    if (this.InvokeRequired)//line:527
    {
        this.BeginInvoke(new Action(() => UpdateProgress(current, total, message)));
        return;
    }

    // ===== 设置进度条范围 =====
    progressBar.Maximum = Math.Max(total, 1);
    progressBar.Value = Math.Min(current, progressBar.Maximum);

    // ===== 计算百分比 =====
    int percent = total > 0 ? current * 100 / total : 0;

    // ===== 更新文字标签 =====
    lblProgress.Text = string.IsNullOrEmpty(message)
        ? $"{percent}%  {current}/{total}"
        : $"{message}  {percent}%  {current}/{total}";
}

逐段说明

作用 细节
527-531 UI 线程安全 WinForms 控件只能在创建它们的线程(UI 主线程)上操作。刷写逻辑运行在后台线程(Task.Run),所以 InvokeRequired 检查是否跨线程。若是,用 BeginInvoke 异步投递到 UI 线程重新执行,避免死锁和跨线程异常
532 设置进度条上限 Math.Max(total, 1) 防止 total 为 0 时进度条报错(ProgressBar 最大值不能为 0)
533 设置当前进度 Math.Min(current, total) 防止 current > total 越界
534 算百分比 total > 0 防除零
535-537 设置文字 message(如步骤名)时前置显示,否则仅显示百分比和计数

调用链

UpdateProgress 通过事件订阅触发,在 SetupEvents() 中注册:

csharp 复制代码
Utils.Common.OnProgress += UpdateProgress;

刷写引擎内部通过 Common.ShowProgress(current, total, message) 触发,实现解耦。帧率由 Common 内部节流控制,避免 UI 线程被高频轰炸。

相关推荐
曹牧2 小时前
C#:`JsonConvert.DeserializeObject`
windows·c#
冷咖啡离 我的笨笨3 小时前
数据去重:通过 C# 删除 Excel 中的重复行
开发语言·c#·excel
鱼听禅6 小时前
C#学习笔记-添加编译参数到程序集自动更新程序编译时间
笔记·学习·c#
不正经学生7 小时前
C语言指针进阶:const 和野指针——给指针加锁,向野指针宣战
c语言·开发语言·c++·算法·c#
czhc11400756637 小时前
# ProcessJob 构造函数 — 语法与概念
c#
用户298698530148 小时前
无需安装 Excel,也能轻松将 CSV 转为 XLS 或 XLSX
后端·c#·excel
在世修行9 小时前
从零打造 C# 工业视觉检测系统(五):相机连接、连续取流与双路实时预览
数码相机·c#·视觉检测
JckOLF04Z9 小时前
C#客户端的异步操作
开发语言·c#
曹牧9 小时前
C#:注释嵌套
开发语言·c#