在后台使用非托管库时无法更新 WPF GUI
我在尝试使用 Emgu 从网络摄像头捕获图像时遇到了问题。为了完成此任务,Emgu 使用非托管 opencv 库。所以问题是我无法从 System.Timers.Timer Elapsed 事件更新我的 GUI(WPF 图像控件)。我知道它在不同的线程中运行,但是嘿,这就是我使用调度程序的原因。这是我第一次用 Dispatcher 做不到。收到 InvalidOperationException 并显示“调用线程无法访问此对象,因为另一个线程拥有它。”。我花了一整天的时间寻找解决方案,但仍然无法解决。任何想法为什么会发生?
webcam.OnNewFrame += newBitmapSource => this.imgCaptured.Dispatcher.Invoke
(
new Action(delegate
{
this.imgCaptured.Source = newBitmapSource;
}),
DispatcherPriority.Background
);
堆栈跟踪上的最后一件事是: System.Windows.Threading.Dispatcher.VerifyAccess()
但是,如果我调用 Dispatcher.CheckAccess() 它会返回 true。
更新:
最后我自己发现了:BitmapSource 必须在 UI 线程上创建。看来它不能以其他方式使用这个对象。
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
);
The last thing on Stack Trace is: System.Windows.Threading.Dispatcher.VerifyAccess()
However, if I call Dispatcher.CheckAccess() it returns true.
UPDATE:
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试将其设置为非后台线程。我想知道这是否是一个问题 - 从后台线程更新 UI。
另外,它表示您必须先冻结位图资源,然后再尝试在不同线程(工作线程和 UI 线程)之间共享它们。请参阅以下链接。
WPF 调度程序 {"调用线程不能访问此对象,因为不同的线程拥有它。"}
http://social.msdn.microsoft.com/Forums/en-US/windowswic/thread/9223743a-e9ae-4301-b8a4-96dc2335b686
Did you try setting it to Non-Background thread. I wonder if that is an issue - updating UI from background thread.
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 {"The calling thread cannot access this object because a different thread owns it."}
http://social.msdn.microsoft.com/Forums/en-US/windowswic/thread/9223743a-e9ae-4301-b8a4-96dc2335b686