2014-01-09 84 views
0

我有WPF用户控件需要在Windows窗体中托管MTAThread。解决方案应该与STAThread和MTAThread一起工作。在技​​术上,没有选择在生产环境中更改公寓状态。ElementHost无法在MTAThread中工作

的Program.cs

[MTAThread] 
static void Main() 
{ 
    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false); 
    Application.Run(new Form1()); 
} 

void Form1_Load(object sender, EventArgs e) 
{ 
    Thread t = new Thread(() =>{ 
    host = new ElementHost(); 
    host.Dock = DockStyle.Fill; 
    uc = new UserControl1(); 
    host.Child = uc; 
    }); 
      t.SetApartmentState(ApartmentState.STA); 
      t.Start(); 
      t.Join(); 
      MessageBox.Show(this.Controls.Count.ToString()); 
      //if (this.InvokeRequired) 
      //{ 
      // this.Invoke((Action)(() => { this.Controls.Add(host); })); 
      //} 
      //else 
      { 
       this.Controls.Add(host); 
      } 
      MessageBox.Show(this.Controls.Count.ToString()); 
} 

在这种情况下,现在主机添加到控制,有增加数量,并没有扔在MTAThread任何异常。但WPF用户控件不是呈现。然而,在STAThread中,它抛出一个异常“调用线程无法访问此对象....”

Anyhelp在这将不胜感激。

回答

0

我不完全确定,但最有可能的是ElementHost Windows窗体控件是围绕COM/ActiveX对象的包装。

而且由于COM/ActiveX UI控件本身不是线程安全的,所以它们必须在STA公寓中运行。一个很好的解释可以找到here

所以我认为,你没有真正的选择,必须改变你的入门线程到STA。

+0

感谢您的快速响应。但是,更改为STAThread可能无法实现,因为此COM组件被主机系统称为“代理进程”。然而,我编辑我的代码,现在elementhost被添加到窗体控件,但它不是呈现... – Saqwes

相关问题