New form in another topic

So, I have a stream in my application, the purpose of which is to listen to messages from the server and act in accordance with what it receives.

I had a problem when I wanted to disconnect a message from the server that when the client application receives it, the client application will open a new form. However, this new form instantly freezes.

I think what happens is that the new form is loaded into the same stream as the stream listening on the server, which, of course, is busy listening to the stream, which in turn blocks the stream.

As a rule, for my other functions in the client listening thread, I would use calls to update the user interface of the main form, so I assume that I ask if this is a way to invoke a new form on the main form.

+6
multithreading c # invoke winforms
source share
2 answers

I assume these are Windows Forms and not WPF? From your background thread, you should not try to create any form, control, etc. Or manipulate them. This will only work from the main thread, which has a message loop and can handle Windows messages.

So, so that your code runs in the main thread instead of the background thread, you can use the Control.BeginInvoke method as follows:

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 does not need a response from the main thread, you should use BeginInvoke rather than Invoke. Otherwise, you might get stuck if the main thread is busy waiting in the background thread.

+15
source share

Basically, you yourself gave the answer - just execute the code to create the form in the GUI stream using Invoke.

0
source share

All Articles