C# 暂停更新进度条
(很抱歉标题不太好,我不知道如何解决我的问题,因此我需要问什么问题:) 上下文 我使用进度条通知用户任务的进度。事实上,这项任务分两步完成,每一步大约占总执行时间的一半。在开始第二项任务之前,我只知道它的长度(因为它取决于前一项任务的结果),所以我无法在一开始就知道最大进度。这就是为什么我在第二个任务之前更改进度条的最大进度 我基本上就是这样做的:C# 暂停更新进度条,c#,winforms,progress-bar,C#,Winforms,Progress Bar,(很抱歉标题不太好,我不知道如何解决我的问题,因此我需要问什么问题:) 上下文 我使用进度条通知用户任务的进度。事实上,这项任务分两步完成,每一步大约占总执行时间的一半。在开始第二项任务之前,我只知道它的长度(因为它取决于前一项任务的结果),所以我无法在一开始就知道最大进度。这就是为什么我在第二个任务之前更改进度条的最大进度 我基本上就是这样做的: // 1st step progressBar.Maximum = step1Objects.Count * 2; // "2" because t
// 1st step
progressBar.Maximum = step1Objects.Count * 2; // "2" because the step will take
// half of the total process
progressBar.Value = 0;
foreach (SomeObject step1Object in step1Objects) {
// Build step2Objects
progressBar.Value = ++progress;
}
// At this moment, the progress bar is half filled
// 2nd step
progressBar.Maximum = step2Objects.Count * 2;
progressBar.Value = step2Objects.Count;
// When we start this step, the progress bar is already half filled
foreach (SomeObject step2Object in step2Objects) {
// Do something
progressBar.Value = ++progress;
}
// At this moment, the progress bar is totally filled
问题
当我到达这一行时:
progressBar.Maximum = step2Objects.Count * 2;
。。。由于与step2Objects.Count
相比,step1Objects.Count
非常少,因此进度条暂时不再占满一半。进度条就是这样做的(这就是用户看到的):
问题:
我怎样才能避免这个“小故障”
我认为要做的事情是在两个步骤之间停止刷新进度条。我的想法是/,但它似乎不存在于进度条中…您写道,这两项任务大约占总执行时间的一半
progressBar.Maximum = 100;
var stepPercentage = 50 / step1Objects.Count;
foreach(SomeObject step1Object in step1Objects)
{
progressBar.Progress += stepPercentage;
}
progressBar.Progress = 50;
stepPercentage = 50 / step2Objects.Count;
foreach(SomeObject step2Object in step2Objects)
{
progressBar.Progress += (stepPercentage + 50);
}
使用标准值,例如100或200。现在除以二。第一步一半,第二步一半。现在您知道第一步有多少项了,所以将50%除以这些项,得到第一步中每个对象完成的数量。这意味着,一旦第一步完成,进度条的50%将被填满。现在,将下一个50%除以步骤2对象的数量,并将每个对象的x数量添加到已填充的50%。将最大进度条设置为步骤1对象。计数*步骤2对象。计数*2
progressBar.Maximum = step1Objects.Count * step2Objects.Count * 2;
然后在循环中,尝试:
progressBar.Value = 0;
//phase 1
foreach (SomeObject step1Object in step1Objects) {
// Build step2Objects
progress = progress + step2Objects.Count;
progressBar.Value = progress;
}
//phase 2
foreach (SomeObject step2Object in step2Objects) {
// Do something
progress = progress + step1Objects.Count;
progressBar.Value = progress;
}
progressBar.Value = 0;
//phase 1
foreach (SomeObject step1Object in step1Objects) {
// Build step2Objects
progress = progress + step2Objects.Count;
progressBar.Value = progress;
}
//phase 2
foreach (SomeObject step2Object in step2Objects) {
// Do something
progress = progress + step1Objects.Count;
progressBar.Value = progress;
}