文章目录
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 线程被高频轰炸。