使用 async/await:太早等待 returns

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();returns太早了,进度80%左右就已经出现ok消息框了。

我做错了什么?

您遇到的问题与您正确使用的 async/await 无关。 await 不是返回太早,只是进度条更新太晚了。换句话说,这是几个线程中描述的进度条控件特定问题 - Disabling .NET progressbar animation when changing value?, Disable WinForms ProgressBar animation, The RunWorkerCompleted is triggered before the progressbar reaches 100% 等。您可以使用这些线程中提供的解决方法之一。

为了安全起见为什么不移动

MessageBox.Show("ok");

进入 Continue with so:

            await ConvertFiles().ContinueWith((t) => { MessageBox.Show("ok"); });

这确保它仅在任务完成时运行