ProgressBar不从异步任务更新

时间:2016-01-22 15:38:55

标签: c# asynchronous async-await task

我正在尝试将旧项目从BackgroundWorker转换为异步/等待,但我真的很难让进度条更新。我遵循了这篇文章,但却无法像以前一样工作:

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

我哪里错了?这让我很生气。感谢。

1 个答案:

答案 0 :(得分:6)

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

使用float或更改操作顺序:i * 100 / total