【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 线程被高频轰炸。

相关推荐
BruceNeter1 天前
C# winform卡死问题分析1——线程池子线程创建句柄
c#·.net
何以解忧唯有撸码3 天前
开源】当桌面图标开始打台球:我用 WinForms 做了一桌“真的”台球
c#·winform·自定义控件·gdi
国家一级摸鱼选手3 天前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
汤姆宝库4 天前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
Risehuxyc4 天前
C# 发展历史
开发语言·c#
kyle~4 天前
C# --- 反射
开发语言·c#
暴走约伯5 天前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
用户788477316346 天前
WinForms 迁移 WPF:Upgrade Assistant 覆盖 30%,剩下 70% 我手写了六周
c#
寂寞的船6 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
用户3721574261357 天前
C# 提取 PDF 附件:包括文档附件和页面注释附件
c#