在线程中创建新表单(Csharp) [英] Create new form in thread (Csharp)

查看:166
本文介绍了在线程中创建新表单(Csharp)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
在C#中,如何在线程中创建新表单?

Hello,
In C#, how can I create a new form in thread ?

//----- Begin Thread // Recieve Data From Socket
while (True)
{

Test (AccesMethodNewFom()); // if the ChatWindow is not open will ...
}

//-----End Thread

//-----AccesMethodNewFom() // Open the ChatWindow

Form F=new Form();
//.... blablabla ....
F.show()


请注意,我想使用"F.show()"而不是"Application.run(F)"
请问我的毕业设计 plz 有什么解决办法吗?
非常感谢您...


Notice I ''d like to use "F.show()" not "Application.run(F)"
Any solution for my graduation project, plz, please?
Thank you very much...

推荐答案

我建​​议您使用一种最近被发明的东西(称为搜索引擎)的服务,并使用诸如以下的搜索词 c#在线程中创建表单或类似方法.
I would recommend that you employ the services of one of the recently invented things called a search engine, with a search term something like c# create form in thread, or similar.


虽然您使用Form的方式是正确的,但在单独的线程上显示通常不起作用,但是不是您在想的原因.
当您执行新线程时,例如:

While you are somewhat right in that using Form.Show on a separate thread doesn''t generally work, it''s not for the reasons you''re thinking.

When you do a new thread such as in:

Thread t = new Thread(OpenNewForm);
t.Start();



只要该方法完成(在本例中为OpenNewForm),该线程就会消失",杀死其中的所有内容.因为您使用的是.Show(),所以该方法将完成.

但是,如果您使用.ShowDialog(),则直到该线程关闭,该线程才会完成.

而且,即使我知道这可行,我还是像这样测试了它:



whenever that method completes (in this case OpenNewForm), the thread will "go away" killing anything within it. Because you''re using .Show(), the method will complete.

If however, you used .ShowDialog(), the thread will not finish until that thread is closed.

And, even though I know this works, I just tested it like so:

private void button1_Click(object sender, EventArgs e)
{
  Thread t = new Thread(OpenNewForm);
  t.Start();
}

private void OpenNewForm()
{
  Form1 newForm = new Form1();
  newForm.ShowDialog();
}



这样做可以...您甚至可以关闭主窗体,直到关闭newForm并允许线程完成后,应用程序才会关闭.



Doing this works...you can even close the main form and the application won''t close until newForm is closed and the thread has been allowed to complete.


代码的方式目前,您将无限创建一个新表格.这将导致在系统崩溃之前立即创建成百上千的表单,我们回到这里询问您为什么线程创建了这么多表单.

您的线程方法应实例化表单,除非您有未向我们展示的代码,否则所有要做的就是创建一堆空表单.

最后,您实例化和显示表单的方式应该可以正常工作.你有什么问题?
The way your code is currently stated, you''re going to create a new form infinitely. This will result in many hundreds of forms instantly created before your system crashes, and we see you back here asking why your thread is creating so many forms.

Your thread method should instantiate the form, and unless you''ve got code that you''re not showing us, all this is going to do is create a bunch of empty forms.

Finally, the way you''re instantiating and showing the form should work fine. What problem are you having?


这篇关于在线程中创建新表单(Csharp)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆