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

相关推荐
Behaviour7 小时前
Unity UI循环列表UIScrollViewContent实现
ui·unity·c#·游戏引擎
c#上位机7 小时前
C#上位机项目实战——C#的dll项目编译时拷贝到指定目录下
开发语言·c#
曹牧8 小时前
C#:数组与列表的差异
开发语言·c#
何以解忧唯有撸码8 小时前
Winform上位机也能写出媲美Avalonia的界面
c#·源码·自定义控件
格林威11 小时前
C#图像快速剪切:使用OpenCvSharp和Halcon优化图像剪切和CPU占用
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机
格林威14 小时前
C#图像分块处理:图像按行或按块(Tile)切分,多个 CPU 核心同时处理不同的区域
开发语言·图像处理·人工智能·机器学习·计算机视觉·c#·工业相机
雪隐14 小时前
WPF + MVVM 实战系列04-我摔了 5 次,你看着绕
c#
消费知多少15 小时前
解析勤策签约大西洋焊接费用核销实践案例
开发语言·c#
CSDN_RTKLIB15 小时前
HashSet、Dictionary
c#
曹牧16 小时前
C#与Java后台交互
java·windows·microsoft·c#