我仍然遇到如何在我在这里讨论的单独的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) 我有一个主UI线程,它运行应用程序并创建主窗口表单(让我们称之为W
).我还有一个辅助线程,我旋转并创建一个对话框(让我们称之为B
).
我想将对话框的所有者设置B
为主窗口W
.B
s所有者的设置发生在创建的线程上B
.基本上:
b.Owner = w;
Run Code Online (Sandbox Code Playgroud)
但这会引发一个跨线程异常,告诉我我正在尝试W
从错误的线程访问该对象.
于是,我就用主UI线程上执行代码,Control.Invoke
上W
.但是,我得到同样的错误,告诉我我正在尝试B
从错误的线程访问:
System.InvalidOperationException was unhandled by user code
Message=Cross-thread operation not valid: Control 'B' accessed from a
thread other than the thread it was created on.
Source=System.Windows.Forms
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?