Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update the GUI on the parent form when I retrieve the value from a Task?

I think I'm missing something obvious here, but how do I update the GUI when using a task and retrieving the value? (I'm trying to use await/async instead of BackgroundWorker)

On my control the user has clicked a button that will do something that takes time. I want to alert the parent form so it can show some progress:

private void ButtonClicked()
        {
            var task = Task<bool>.Factory.StartNew(() =>
            {
                WorkStarted(this, new EventArgs());
                Thread.Sleep(5000);
                WorkComplete(this, null);
                return true;
            });

            if (task.Result) MessageBox.Show("Success!");//this line causes app to block
        }

In my parent form I'm listening to WorkStarted and WorkComplete to update the status bar:

myControl.WorkStarting += (o, args) =>
                {
                    Invoke((MethodInvoker) delegate
                        {
                            toolStripProgressBar1.Visible = true;
                            toolStripStatusLabel1.Text = "Busy";
                        });

                };

Correct me if I'm wrong, but the app is hanging because "Invoke" is waiting for the GUI thread to become available which it won't until my "ButtonClicked()" call is complete. So we have a deadlock. What's the correct way to approach this?

like image 269
Kim Avatar asked Oct 20 '22 23:10

Kim


1 Answers

You're blocking the UI thread Task.Result blocks until the task is completed.

Try this.

private async void ButtonClicked()
{
     var task = Task<bool>.Factory.StartNew(() =>
     {
            WorkStarted(this, new EventArgs());
            Thread.Sleep(5000);
            WorkComplete(this, null);
            return true;
     });

     await task;//Wait Asynchronously
     if (task.Result) MessageBox.Show("Success!");//this line causes app to block
}
like image 193
Sriram Sakthivel Avatar answered Oct 24 '22 11:10

Sriram Sakthivel