0

i have a TCP server app and have a thread for communicating with TCP clients. When i receive a data from a client i want to create a new form by using this data but i can not create the form in a thread. I can easily create the form using button click event.

Where am i wrong?

Thank you.

sanchop22
  • 2,729
  • 12
  • 43
  • 66

3 Answers3

3

To avoid such situations, it is better to let the applications original UI-thread handle the creation of new forms and not have multiple UI-threads. Fortunately, you can invoke operations on that thread.

See here on how to do it on WinForms or here to do it in WPF/Silverlight.

Community
  • 1
  • 1
LueTm
  • 2,366
  • 21
  • 31
  • 2
    -1. FACTUALLY WRONG. I see that often - sorry- programmers not knowing anything then talking. ANY thread can OPEN a form as ong as it runs a dispatcher, and it is trivial to make one. I have an app here having one thread per "main" window (running 8 of them siometimes doing heavy data processing). http://stackoverflow.com/questions/4698080/spawn-a-new-thread-to-open-a-new-window-and-close-it-from-a-different-thread has example code. The create form method opens the form, then runs a dispatcher. Trivial. – TomTom Apr 30 '12 at 08:50
  • @TomTom - yes, of course other threads can be UI threads, create windows and get/dispatch messages. If they could not, there would be only one process:) In this case, the client thread wold have to run a dispatcher to process messages - fine if you don't have to make blocking calls. In the OP case, I'm not sure if running a GUI thread per client is a good idea or not. – Martin James Apr 30 '12 at 09:15
  • Me neither. But that is not the point - the answer was simply wrong, indicating that only "THE" ui thread can create forms, which implies it is only one. – TomTom Apr 30 '12 at 09:43
  • @TomTom: I corrected the statement. I agree it was written a little carelessly. – LueTm Apr 30 '12 at 13:23
1

Sample code to do the job:

  private void Button1_Click(object sender, EventArgs e)
{
    Thread t1 = new Thread(StartMe);
    t1.Name = "Custom Thread";
    t1.IsBackground = true;
    t1.Start();
}

private void StartMe()
{
    //We are switching to main UI thread.
    TextBox1.Invoke(new InvokeDelegate(InvokeMethod), null); 
}

public void InvokeMethod()
{
    //This function will be on main thread if called by Control.Invoke/Control.BeginInvoke
    MyForm frm = new MyForm();
    frm.Show();
}
Romil Kumar Jain
  • 20,239
  • 9
  • 63
  • 92
0

You have to change context to the GUI thread somewhere to create the new form - somewhere, you are going to need to BeginInvoke() something.

What kind of server is this - is a 'classic' synchronous server where there is one listening thread and a server<>client thread for each client connection?

You don't want to create the form upon client connect, you only want to create this form when a connected client specifically asks, yes?

Martin James
  • 24,453
  • 3
  • 36
  • 60