简体   繁体   English

C#在线程中创建新表单

[英]C# New Form Creating In A Thread

i have a TCP server app and have a thread for communicating with TCP clients. 我有一个TCP服务器应用程序,并且有一个用于与TCP客户端通信的线程。 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. 谢谢。

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. 为了避免这种情况,最好让应用程序原始的UI线程处理新表单的创建,并且不要有多个UI线程。 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. 这里关于如何做它的WinForms或在这里做,在WPF / Silverlight的。

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();
}

You have to change context to the GUI thread somewhere to create the new form - somewhere, you are going to need to BeginInvoke() something. 您必须在某处将上下文更改为GUI线程以创建新表单-在某处,您将需要BeginInvoke()。

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? 这是哪种服务器-是“经典”同步服务器,其中每个客户端连接都有一个侦听线程和一个server <> client线程?

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? 您不想在客户端连接时创建表单,仅在连接的客户端明确询问时才创建此表单,是吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM