ProgressBar没有从异步任务更新

ProgressBar没有从异步任务更新

问题描述:

我想从BackgroundWorker的旧项目过渡到异步/等待,但我真的很努力获取进度条更新。我跟着这篇文章,但不能因为他们做得到它的工作:ProgressBar没有从异步任务更新

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

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

+0

究竟不起作用?你有错误吗?或者进度条没有更新? –

+1

对不起,忘记了一个非常关键的信息。进度条不更新,但其余的GUI(状态栏)是。进度条甚至没有从0到100跳跃,它只是没有做任何事情。 – tom982

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

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

+0

非常感谢。我确信这是异步相关的,因为我对它很陌生,实际上它正盯着我。现在完美工作。 – tom982