为什么progressBar显示从结束到开始向后计数的进度?

时间:2016-02-17 08:11:27

标签: c# .net winforms

$('#twothree a')

变量int countUploadMsg = 0; private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { int counter = 0; allLoadedMessages = new List<OpenPop.Mime.Message>(); OpenPop.Mime.Message loadedMessage = null; DirectoryInfo di = new DirectoryInfo(@"e:\test\"); FileInfo[] files = di.GetFiles(); foreach (FileInfo file in files) { loadedMessage = OpenPop.Mime.Message.Load(file); allLoadedMessages.Add(loadedMessage); int nProgress = (files.Length - counter + 1) * 100 / files.Length; backgroundWorker2.ReportProgress(nProgress); counter += 1; } } private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e) { pbt1.Value = e.ProgressPercentage; pbt1.Text = e.ProgressPercentage.ToString() + "%"; pbt1.Invalidate(); lvnf.Items.Add(new ListViewItem(new string[] { allLoadedMessages[countUploadMsg].Headers.From.ToString(), //From Column allLoadedMessages[countUploadMsg].Headers.Subject, //Subject Column allLoadedMessages[countUploadMsg].Headers.DateSent.ToString() //Date Column })); countUploadMsg += 1; } pbt1

我看到ProgressBar绿色为100%,文字也是100%,然后开始向后移动绿色和文字100%99%98%....

也许我正在做的计算:

ProgressBar

int nProgress = (files.Length - counter + 1) * 100 / files.Length; 也应该是files.Length

1 个答案:

答案 0 :(得分:3)

是的,你做得对。这是你的计算。

int nProgress = (files.Length - counter + 1) * 100 / files.Length;

由于counter,您的counter += 1;正在增加,而您的files.Length是不变的。然后由于上述计算,nProgress肯定会越来越少。因此,您可以100%降至0%。

如果你不这样做,那就是:使用计数器作为渐进指标?

int nProgress = counter * 100 / files.Length; //use counter here...

此外,您可能希望在调用后台工作进度之前增加计数器:

foreach (FileInfo file in files)
{
    loadedMessage = OpenPop.Mime.Message.Load(file);
    allLoadedMessages.Add(loadedMessage);
    counter += 1; //put before the progress;
    int nProgress = counter * 100 / files.Length;
    backgroundWorker2.ReportProgress(nProgress);
}