使用async / await:await返回得太早

时间:2016-01-07 15:52:49

标签: c# winforms asynchronous async-await progress-bar

我有一个简单的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%的进度。

我做错了什么?

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:0)

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

MessageBox.Show("ok");

进入一个继续所以:

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

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

相关问题