我正在尝试将旧项目从BackgroundWorker转换为异步/等待,但我真的很难让进度条更新。我遵循了这篇文章,但却无法像以前一样工作:
这是我的代码:
private async void btnStart_Click(object sender, EventArgs e)
{
btnStart.Enabled = false;
pb.Show();
btnCancel.Enabled = true;
var progressIndicator = new Progress<int>(ReportProgress);
List<string> updates = Directory.GetFiles(txtInput.Text).ToList();
try
{
await ProcessUpdates(updates, progressIndicator, _cts.Token);
}
catch (OperationCanceledException ex)
{
MessageBox.Show(ex.Message, "Operation Cancelled");
}
btnStart.Enabled = true;
pb.Hide();
btnCancel.Enabled = false;
}
async Task<int> ProcessUpdates(List<string> updatePaths, IProgress<int> progress, CancellationToken ct)
{
int total = updatePaths.Count;
for (int i = 0; i < updatePaths.Count; i++)
{
ct.ThrowIfCancellationRequested();
string update = updatePaths[i];
ssFile.Text = $"Processing update: {Path.GetFileName(update)}";
using (Stream source = File.Open(update, FileMode.Open))
using (Stream destination = File.Create(txtOutput.Text + "\\" + Path.GetFileName(update)))
{
await source.CopyToAsync(destination);
}
progress?.Report((i / total) * 100);
}
return total;
}
private void ReportProgress(int value)
{
pb.Value = value;
}
private void btnCancel_Click(object sender, EventArgs e)
{
_cts.Cancel();
}
我哪里错了?这让我很生气。感谢。
答案 0 :(得分:6)
(i / total) * 100
执行整数除法,它总是截断小数部分,结果为0
,因为i
小于total
。
使用float
或更改操作顺序:i * 100 / total