Win32容器的WPF线程问题 [英] WPF threading issue with Win32 container

查看:68
本文介绍了Win32容器的WPF线程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在尝试将现有的WPF窗口集成到Win32容器应用程序中. Win32应用程序可以集成并仅显示Winforms Usercontrols.由于我们已经有一个运行中的WPF窗口代码,因此我们使用了元素主机,并使用了元素主机内部窗口的内容呈现器将其显示为winforms用户控件.
WPF窗口代码将覆盖受保护的虚拟虚空OnInitialized(EventArgs e)函数,并首先调用base.OnInitialized,然后调用
自定义代码.

问题在于,您可以从win32容器中为第一个实例运行以下代码,但是当我们执行相同的代码时,可以为第二个实例运行以下代码
代码,它引发错误初始化时,调用线程无法访问该对象,因为其他线程拥有它."

We are trying to integrate existing WPF window on to Win32 container application. The win32 application can integrate and show only Winforms Usercontrols. Since we already have a running WPF window code, we used the element host and we used the content presenter of the window inside the element host to show as a winforms usercontrol.
The WPF window code overrides the function protected virtual void OnInitialized(EventArgs e) and calls first base.OnInitialized and then
the custom code.

The issue is here is that you can run the below code for the first instance from win32 container , but second instance when we execute same
code , it throws the error "The calling thread cannot access this object because a different thread owns it." from the line base.OnInitialized when initialization

AutoUpdate window = new Autoupdate(); 


即使我们在调度程序下使用下面的代码,它也会在firstime之后引发相同的错误.


Even if we use the below code under dispatcher it throws the same error after the firstime.

ElementHost elementHost = new ElementHost();
                      elementHost.Dock = DockStyle.None;
                      elementHost.Width = 150;
                      elementHost.Height = 50;
                      AutoUpdate window = new Autoupdate();
                      ContentPresenter pres = new ContentPresenter();
                      pres.Content = window.Content;
                      elementHost.Child = pres;
                      this.Controls.Add(elementHost);

推荐答案

好吧,实际上ElementHost在其中显示了整个WPF应用程序.

我认为,它不允许您从外部(winforms appliction)更新诸如ContentPresenter之类的控件.

我认为公开一种方法可以为您创建ContentPresenter是一个好习惯.

Sacha Barbar提出了一个很好的扩展,可以处理跨线程问题.您可以看一下.
检查一下:
Well, actually ElementHost displays the whole WPF app within it.

I think, it does not allow you to update controls like ContentPresenter from outside(winforms appliction).

I think it would be a good practice to expose one method which will create this ContentPresenter for you.

Sacha Barbar proposed a good extension to work with Cross thread issues. You might take a look into it.
Check this :
public static void InvokeIfRequired(this DispatcherControl control, Action operation)
{
  if (control.Dispatcher.CheckAccess())
  {
    operation();
  }
  else
  {
    control.Dispatcher.BeginInvoke(DispatcherPriority.Normal, operation);
  }
}


这篇关于Win32容器的WPF线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆