我试图从线程打开窗口,但打开的窗口被冻结了。 第一个窗口中的代码(在线程内):
MyProject.MainModuleWindow mmw = new MyProject.MainModuleWindow();
mmw.Show();
如何正确地做到这一点?
答案 0 :(得分:0)
尝试将帖子的ApartmentState
设置为ApartmentState.STA
。
var thread = new Thread(new ThreadStart(OpenAWindow));
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
新创建的帖子的default ApartmentState是MTA。
New threads are initialized as ApartmentState.MTA if their apartment state
has not been set before they are started.
当您使用窗口或对话框进行操作时,需要手动将其设置为ApartmentState.STA
。
你需要设置线程的ApartmentState的根本原因是你的窗口interop with COM:
Because COM classes use apartments, the common language runtime needs to
create and initialize an apartment when calling a COM object in a COM
interop situation.
在Windows和.NET环境中都是如此,我不知道这是否适合您的情况。尝试一下。