2016-01-22 72 views
0

我想從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

回答

5

(i/total) * 100執行整數除法,總是截斷小數部分,導致值爲0,因爲i小於total

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

+0

非常感謝。我確信這是異步相關的,因爲我對它很陌生,實際上它正盯着我。現在完美工作。 – tom982