gpt4 book ai didi

c# - 刷新进度条

转载 作者:行者123 更新时间:2023-11-30 21:57:18 25 4
gpt4 key购买 nike

我想在 C# WPF 中刷新进度条。

这个问题听起来很简单,我应该可以谷歌一下。但我看到的解决方案并不令我满意。

假设我必须运行一个很长的算法,例如5 个不同的步骤。我不知道计算不同的步骤需要多长时间。但我知道我编程了什么,我可以使用分析器来检查 CPU 在每个步骤中使用了多少时间(以所有步骤总时间的百分比表示)。

这可能是时间例如:

Method1() takes 3s
Method2() takes 5s
Method3() takes 1s

这是我的方法:

“简单”方法:

ProgressBar pb = new ProgressBar()
{
// The total duration of all methods
Maximum = 9
};

Method1();
// + 3 for 3 seconds
pb.Value += TimeForMethod1;

Method2();
// + 5 for 5 seconds
pb.Value += TimeForMethod2;

Method3();
// + 1 for 1 second
pb.Value += TimeForMethod3;

这很简单。但是有一个问题。这会阻塞我的 UI 线程 9 秒,这太可怕了(因为用户可能认为程序已经崩溃)。

所以使用线程似乎很明显..


“线程”方法:
这有一个问题,我需要调度 ProgressBar 上的每个操作,这可能非常慢(对于 ProgressBar 上的大量更新)

我为此编写了一个“TaskQueue”。我可以将我想做的所有工作保存在 Queue 中,并且 ThreadRun 被调用并更新 之后正在处理所有这些任务>ProgressBar(和一个 Label)在任务之间。

我不想发布 ThreadQueue 的所有代码,因为它的实现非常好,也许还不是很好(还)。

这是线程方法的重要部分:

foreach (var threadQueueNode in threadQueue)
{
// Changes e.g. a label displaying what the thread is doing next
threadQueueNode.PreMainFunction.Invoke();

// Executes the main task
this.Result = threadQueueNode.MainFunction.Invoke();

// Updates the ProgressBar after the work is done.
threadQueueNode.PostMainFunction.Invoke();
}

PostMainFunction 是一个 Delegate,例如这个:

PostMainFunction = (Action<int>)((value) => this.Dispatcher.Invoke(() => this.ProgressBarStatus.Value += value));

对于像我这样的问题,更新 ProgessBar 的专业方法是什么?
我很乐意进行讨论。

感谢您的帮助和抽出时间!

最佳答案

BackgroundWorker 清晰易读:

var bw = new BackgroundWorker();

bw.DoWork += (s, e) =>
{
var worker = s as BackgroundWorker;
Method1();
worker.ReportProgress(30);
Method2();
worker.ReportProgress(80);
Method3();
worker.ReportProgress(100);
};

bw.ProgressChanged += (s, e) =>
{
pb.Value += e.ProgressPercentage;
};

bw.RunWorkerCompleted += (s, e) =>
{
};

bw.RunWorkerAsync();

关于c# - 刷新进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30827847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com