如何正确打开一个线程内的窗口?

时间:2014-02-23 01:27:50

标签: c# multithreading xamarin gtk#

我试图从线程打开窗口,但打开的窗口被冻结了。 第一个窗口中的代码(在线程内):

MyProject.MainModuleWindow mmw = new MyProject.MainModuleWindow();
mmw.Show();

如何正确地做到这一点?

1 个答案:

答案 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环境中都是如此,我不知道这是否适合您的情况。尝试一下。