7

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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Dan
  • 257
  • 1
  • 3
  • 11

2 Answers2

17

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.

Josh
  • 68,005
  • 14
  • 144
  • 156
  • This is a great idea, and a good solution, but what if there is no main form created yet? As in you want to create a form on the main thread from any thread without any warranty that there is an active main form. Is there a solution one could use in that case? – Adam L. S. Jun 09 '21 at 10:13
0

You basically gave the answer yourself - just execute the code to create the form on the GUI thread, using Invoke.

Jim Brissom
  • 31,821
  • 4
  • 39
  • 33