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

相关推荐
Neil201315 分钟前
ajax跨域请求
c#
唐青枫1 小时前
别把 Razor 当成几段 HTML:C#.NET Razor Pages、MVC 视图与实战详解
c#·.net
专注仿真7 小时前
CMO模型文档-活动单元基类
c#·模型·cmo·活动单元基类
我是苏苏9 小时前
Agent 开发实战 :C#实现语义检索!向量数据库Qdrant的下载安装及调试步骤
c#·ai编程
光泽雨10 小时前
IEnumerable<T> 详细讲解
c#·c
Lost of 程序猿10 小时前
.NET 10 船端单机部署与离线升级实战:从闪退事故到无感回滚
c#·asp.net·.net
淡海水11 小时前
11-04-Unity-Span-foreach-LINQ的分配与热路径边界
unity·c#·linq·foreach·span
唐青枫1 天前
对象到底住在哪里?C#.NET 托管堆从分配、GC 到内存排查
c#·.net
fogota1 天前
Emoji与Segoe MDL2 Assets的比较
c#·wpf
灸木1 天前
C# 多线程与异步
c#