开发者

Multi-threaded multi-windowed application not working

I want to create a program that does remote installs. I'd like to be able to have a win开发者_运维百科dow 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜