使用异步/等待:await返回太早(Using async/await: await returns too early)
我有一个模拟的Windows窗体应用程序,只有一个按钮和一个进度条。
然后我有这个代码:
private async void buttonStart_Click(object sender, EventArgs e) { progressBar.Minimum = 0; progressBar.Maximum = 5; progressBar.Step = 1; progressBar.Value = 0; await ConvertFiles(); MessageBox.Show("ok"); } private async Task ConvertFiles() { await Task.Run(() => { for (int i = 1; i <= 5; i++) { System.Threading.Thread.Sleep(1000); Invoke(new Action(() => progressBar.PerformStep())); } }); }
await ConvertFiles();
返回太早,ok消息框已经出现在大约80%的进度。我究竟做错了什么?
I have a simly Windows Forms app with just a button and a progressbar on it.
Then I have this code:
private async void buttonStart_Click(object sender, EventArgs e) { progressBar.Minimum = 0; progressBar.Maximum = 5; progressBar.Step = 1; progressBar.Value = 0; await ConvertFiles(); MessageBox.Show("ok"); } private async Task ConvertFiles() { await Task.Run(() => { for (int i = 1; i <= 5; i++) { System.Threading.Thread.Sleep(1000); Invoke(new Action(() => progressBar.PerformStep())); } }); }
The
await ConvertFiles();
returns too early, the ok messagebox already appears at about 80% progress.What am I doing wrong?
原文:https://stackoverflow.com/questions/34659485
更新时间:2023-12-11 14:12