我正在将字符串值从List <>添加到列表框中。 我想在ReportProgress方法中计算进度百分比。请帮助我计算进度百分比。我在ReportProgress方法的第一个参数中写了0。我想用进度百分比替换那个0。
这是我的代码。
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
List<string> result = new List<string>();
var found = obj.getFiles();
foreach (var item in found)
{
if (item.Contains("SFTP:") || item.Contains("ERROR:"))
{
result.Add(item);
(sender as BackgroundWorker).ReportProgress(0, item);
}
else
(sender as BackgroundWorker).ReportProgress(0);
System.Threading.Thread.Sleep(1000);
}
e.Result = result;
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState != null)
listBox1.Items.Add(e.UserState);
progressBar2.Value = e.ProgressPercentage;
}
答案 0 :(得分:1)
Foreach不一定是此应用程序的最佳迭代。使用for循环并使用索引根据找到的大小来计算进度。
for (int i = 0; i < found.Count; i++)
{
int progress = (int)(((float)(i + 1) / found.Count) * 100);
if (found[i].Contains("SFTP:") || found[i].Contains("ERROR:"))
{
result.Add(found[i]);
(sender as BackgroundWorker).ReportProgress(progress, found[i]);
}
else
(sender as BackgroundWorker).ReportProgress(progress);
System.Threading.Thread.Sleep(1000);
}