Geo*_*uer 8 .net multithreading winforms
我仍然遇到如何在我在这里讨论的单独的UI线程中创建winforms的问题.
在试图解决这个问题时,我编写了以下简单的测试程序.我只是希望它在名为"UI线程"的单独线程上打开一个表单,并且只要表单打开就保持线程运行,同时允许用户与表单交互(旋转是作弊).我理解为什么以下失败并且线程立即关闭但我不确定我应该做些什么来解决它.
using System;
using System.Windows.Forms;
using System.Threading;
namespace UIThreadMarshalling {
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var tt = new ThreadTest();
ThreadStart ts = new ThreadStart(tt.StartUiThread);
Thread t = new Thread(ts);
t.Name = "UI Thread";
t.Start();
Thread.Sleep(new TimeSpan(0, 0, 10));
}
}
public class ThreadTest {
Form _form;
public ThreadTest() {
}
public void StartUiThread() {
_form = new Form1();
_form.Show();
}
}
}
Run Code Online (Sandbox Code Playgroud)
ang*_*son 14
在一个新线程上,调用Application.Run传递表单对象,这将使该线程在窗口打开时运行自己的消息循环.
然后你可以在该线程上调用.Join以使你的主线程等待直到UI线程终止,或者使用类似的技巧来等待该线程完成.
例:
public void StartUiThread()
{
using (Form1 _form = new Form1())
{
Application.Run(_form);
}
}
Run Code Online (Sandbox Code Playgroud)