Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Winforms UI from background thread result

This is probably a silly question, but I could not find an answer on stackoverflow.

I have a button click event in a Winform app that runs a thread to caclulate a result to display in a form.

How do I update the Forms UI when the thread has calculated the result?

    private void btnRequestR2Approval_Click(object sender, EventArgs e)
    {
        if (User.IsLogged)
        {
            ValidationResults results = new ValidationResults();
            results.Show();

            Logger log = Logger.Instance();
            Logger.NewLogAddedHandler messageDelegate = new Logger.NewLogAddedHandler(results.NewLogMessage);

            if (!log.IsEventHandlerRegistered())
            {
                log.NewLogAdded += messageDelegate;
            }

            ThreadStart operation = new ThreadStart(ValidateAndSubmit);
            Thread theThread = new Thread(operation);
            theThread.Start();

        }
        else
        {
            MessageBox.Show("Please login");
        }

    }

Thank you

like image 634
Sergey Avatar asked Jun 11 '09 19:06

Sergey


1 Answers

The simplest technique for executing a background task in WinForms is to use a BackgroundWorker.

  • Drop it onto a form.
  • Wire up the events. As a minimum, use DoWork. You'll probably also want RunWorkerCompleted.
  • Write your background task in the DoWork event.
  • Write any UI changes in the RunWorkerCompleted event.
  • Call backgroundWorker1.RunWorkerAsync(); to kick off the process, probably from some button handler.

Using a BackgroundWorker avoids all the annoying thread handling and IsInvokeRequired stuff.

Here's a more detailed how-to article.

like image 162
Don Kirkby Avatar answered Oct 01 '22 03:10

Don Kirkby