[英]C# Open Form in a new Thread or Task?
How do i open a new form in C#, with the thread or task.如何使用线程或任务在 C# 中打开一个新表单。
example:例子:
public void openform()
{
Form _form = new Form();
_form.show()
}
Thread _thread = new Thread(openform);
_thread.start();
if i use a Thread it opens the form and close it again.如果我使用线程,它会打开表单并再次关闭它。
You can create another UI thread if you simply set the ApartmentState
to STA
and start another message loop:如果您只需将
ApartmentState
设置为STA
并启动另一个消息循环,您就可以创建另一个 UI 线程:
Thread _thread = new Thread(() =>
{
Application.Run(new Form());
});
_thread.SetApartmentState(ApartmentState.STA);
_thread.Start();
Note that you wont't be able to display a control that you create on the main thread on this form though.请注意,您将无法在此窗体的主线程上显示您创建的控件。 That's why it is generally a bad idea to create more than one UI thread.
这就是为什么创建多个 UI 线程通常是一个坏主意的原因。
Thread thd = new Thread(() =>
{
//Do Some stuff
//Do some more stuff
var dispatcher = Dispatcher.CurrentDispatcher;
dispatcher.UnhandledException += Dispatcher_UnhandledException; //you exception handling logic
Dispatcher.Run();
});
thd.IsBackground = true;
thd.SetApartmentState(ApartmentState.STA);
thd.Start();
based on your use case call Dispacther.InvokeShutdown();
根据您的用例调用
Dispacther.InvokeShutdown();
when done.完成后。
通过使用ShowDialog
它仅在窗口关闭时返回:
new Thread(() => new MyForm().ShowDialog()).Start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.