New form on a different thread

Dan picture Dan · Jan 12, 2011 · Viewed 17.2k times · Source

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.

Answer

Josh picture Josh · Jan 12, 2011

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.