在后台使用非托管库时无法更新WPF GUI [英] Cannot Update WPF GUI While Using Unmanaged Libraries In Background

查看:85
本文介绍了在后台使用非托管库时无法更新WPF GUI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试使用Emgu从网络摄像头捕获图像时,我遇到了一个问题.为了执行此任务,Emgu使用非托管的opencv库.所以问题是我无法从System.Timers.Timer Elapsed事件更新GUI(WPF图像控件).我知道它在不同的线程中运行,但是,这就是为什么我使用Dispatcher的原因.这是我第一次无法使用Dispatcher做到这一点.通过调用线程无法访问此对象,因为另一个线程拥有它"来获取InvalidOperationException.我整天都在寻找解决方案,但仍然无法解决.任何想法为什么会发生?

I've enocountered a problem while trying to use Emgu to capture images from a webcam. To do this task, Emgu uses unmanaged opencv libraries. So the problem is that I can't update my GUI (WPF Image control) from System.Timers.Timer Elapsed event. I know it's running in different thread, but hey, that's why I'm using a Dispatcher. It's the first time I can't do it with Dispatcher. Getting InvalidOperationException with "The calling thread cannot access this object because a different thread owns it.". I've spent the whole day searching for a solution, but still couldn't fix it. Any ideas why does it happen?

webcam.OnNewFrame += newBitmapSource => this.imgCaptured.Dispatcher.Invoke
            (
                new Action(delegate
                    {
                        this.imgCaptured.Source = newBitmapSource;
                    }),
                DispatcherPriority.Background
            );

堆栈跟踪的最后一件事是:System.Windows.Threading.Dispatcher.VerifyAccess()

The last thing on Stack Trace is: System.Windows.Threading.Dispatcher.VerifyAccess()

但是,如果我调用Dispatcher.CheckAccess(),它将返回true.

However, if I call Dispatcher.CheckAccess() it returns true.

更新:

最后,我一个人发现了它:BitmapSource必须在UI Thread上创建.似乎无法使用此对象.

Finally I found it out by myself: the BitmapSource had to be created on UI Thread. It seems like it can't use this object otherwise.

推荐答案

您尝试将其设置为非背景"线程.我想知道这是否是一个问题-从后台线程更新UI.

Did you try setting it to Non-Background thread. I wonder if that is an issue - updating UI from background thread.

此外,它说您必须先冻结位图资源,然后再尝试在不同线程(工作线程和UI线程)之间共享它们.请参阅下面的链接.

Also, It says you must freeze Bitmap resources before trying to share them across different threades - worker thread and UI thread. Refer below links.

WPF Dispatcher {调用线程无法访问该对象,因为其他线程拥有它.}

http://social.msdn.microsoft.com/Forums/zh-CN/windowswic/thread/9223743a-e9ae-4301-b8a4-96dc2335b686

这篇关于在后台使用非托管库时无法更新WPF GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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