0

I want to create a program that does remote installs. I'd like to be able to have a window launch at the start of each installation and give a progress bar with the approximate progress of the job.

If I create the window off the main thread I can access all of it's elements but it's not responsive due to the task of actually running the install. If I launch the window in a new thread I can't seem to get the main thread to recognize any of the elements in the window so I can't update the progress bar.

How can I create a multi-threaded UI that is responsive?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
DarkShadow
  • 185
  • 2
  • 4
  • 15

2 Answers2

0

To keep the UI responsive with a second thread (that's doing the work) and be able to update the UI from the second thread, you'll need to use Invoke on the controls. There's a number of code snippets available out there.

Here's a short example: How can I update my user interface from a thread that did not create it?

You can find dozens of examples here on SO as well - just do a search :)

Here's another similar question on SO today - cross threading problem - there's a code example in one of the answers.

Community
  • 1
  • 1
Tim
  • 28,212
  • 8
  • 63
  • 76
0

There's a simple way to access UI controls from other threads safely - to call lambda with Control.BeginInvoke(lambda) method. For example, suppose you have WinForms application with one form and progress bar with button on it. When button is clicked - some imaginary work is going on in separate thread and progress bar should be updated. The simplest would be to write something like that:

private void button1_Click(object sender, EventArgs e)
{
    ThreadStart s = () =>
    {
        for (int i = 0; i <= 10; i++)
        {
            Action a = () => progressBar1.Value = i * 10;
            BeginInvoke(a);
            Thread.Sleep(300); // imitate some workload
        }
    };
    var t = new Thread(s);
    t.Start();
}

The same result could be achieved with BackgroundWorker or other techniques, but this is the most simple as for me.

Ivan Danilov
  • 14,287
  • 6
  • 48
  • 66