0
我想從BackgroundWorker的舊項目過渡到異步/等待,但我真的很努力獲取進度條更新。我跟着這篇文章,但不能因爲他們做得到它的工作:ProgressBar沒有從異步任務更新
這裏是我的代碼:
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();
}
我要去哪裏錯了?這讓我很生氣。謝謝。
究竟不起作用?你有錯誤嗎?或者進度條沒有更新? –
對不起,忘記了一個非常關鍵的信息。進度條不更新,但其餘的GUI(狀態欄)是。進度條甚至沒有從0到100跳躍,它只是沒有做任何事情。 – tom982