ProgressBar 未从异步任务更新

ProgressBar not updating from async task

我正在尝试将一个旧项目从 BackgroundWorker 转换到 async/await,但我真的很难更新进度条。我关注了这篇文章,但无法像他们那样工作:

http://blogs.msdn.com/b/dotnet/archive/2012/06/06/async-in-4-5-enabling-progress-and-cancellation-in-async-apis.aspx

这是我的代码:

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();
}

我哪里错了?这让我发疯。谢谢

(i / total) * 100 执行整数除法,它总是截断小数部分,导致值 0 因为 i 小于 total.

要么使用float,要么改变运算顺序:i * 100 / total