【问题标题】:ElementHost does not work in MTAThreadElementHost 在 MTAThread 中不起作用
【发布时间】:2014-01-10 14:59:54
【问题描述】:

我有 WPF 用户控件,它需要托管在 MTAThread 中的 Windows 窗体中。解决方案应该适用于 STAThread 和 MTAThread。而且从技术上讲,在生产环境中无法更改公寓状态。

程序.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 中,它抛出异常“调用线程无法访问此对象....”

对此的任何帮助将不胜感激。

【问题讨论】:

    标签: wpf elementhost mta


    【解决方案1】:

    我不完全确定,但很可能ElementHost Windows-Forms 控件是 COM/ActiveX-Object 的包装器。

    由于 COM/ActiveX UI 控件本身不是线程安全的,它们必须在 STA 单元中运行。可以在here 找到一个非常恰当的解释。

    所以我认为,您别无选择,必须将您的入口线程更改为 STA。

    【讨论】:

    • 感谢您的快速回复。但是,可能无法更改为 STAThread,因为此 COM 组件被主机系统称为代理进程。但是,我编辑了我的代码,现在 elementhost 已添加到表单控件中,但它没有呈现...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    相关资源
    最近更新 更多