Reputation: 2809
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.
Upvotes: 0
Views: 9538
Reputation: 2380
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.
Upvotes: 3
Reputation: 20745
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();
}
Upvotes: 1
Reputation: 24847
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?
Upvotes: 0