I'm using async/await to asynchronously load my data from database and during the loading process, I want to popup a loading form, it's just a simple form with running progress bar to indicate that there's a running process. After data has been loaded, the dialog will automatically be closed. How can I achieve that ? Below is my current code:
protected async void LoadData()
{
ProgressForm _progress = new ProgressForm();
_progress.ShowDialog() // not working
var data = await GetData();
_progress.Close();
}
Updated:
I managed to get it working by changing the code:
protected async void LoadData()
{
ProgressForm _progress = new ProgressForm();
_progress.BeginInvoke(new System.Action(()=>_progress.ShowDialog()));
var data = await GetData();
_progress.Close();
}
Is this the correct way or there's any better ways ?
Thanks for your help.
ShowDialog()
is a blocking call; execution will not advance to theawait
statement until the dialog box is closed by the user. UseShow()
instead. Unfortunately, your dialog box will not be modal, but it will correctly track the progress of the asynchronous operation.It's easy to implement with
Task.Yield
, like this (WinForms, no exception handling for simplicity):It's important to understand here how the execution flow jumps over to a new nested message loop (that of the modal dialog) and then goes back to the original message loop (that's what
await progressFormTask
is for).You could try the following:
Here's a form that uses Task.ContinueWith and should avoid any race condition with your use of the modal ProgressForm: