简体   繁体   中英

New form on a different thread

So I have a thread in my application, which purpose is to listen to messages from the server and act according to what it recieves.

I ran into a problem when I wanted to fire off a message from the server, that when the client app recieves it, the client app would open up a new form. However this new form just freezes instantly.

I think what's happening is that the new form is loaded up on the same thread as the thread listening to the server, which of course is busy listening on the stream, in turn blocking the thread.

Normally, for my other functions in the clients listening thread, I'd use invokes to update the UI of the main form, so I guess what I'm asking for is if here's a way to invoke a new form on the main form.

I assume this is Windows Forms and not WPF? From your background thread, you should not attempt to create any form, control, etc or manipulate them. This will only work from the main thread which has a message loop running and can process Windows messages.

So to get your code to execute on the main thread instead of the background thread, you can use the Control.BeginInvoke method like so:

private static Form MainForm; // set this to your main form

private void SomethingOnBackgroundThread() {

    string someData = "some data";

    MainForm.BeginInvoke((Action)delegate {

        var form = new MyForm();
        form.Text = someData;
        form.Show();

    });
}

The main thing to keep in mind is that if the background thread doesn't need any response from the main thread, you should use BeginInvoke, not Invoke. Otherwise you could get into a deadlock if the main thread is busy waiting on the background thread.

您基本上自己给出了答案 - 只需执行代码以使用Invoke在GUI线程上创建表单。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM