Cannot Update WPF GUI While Using Unmanaged Libraries In Background

自作多情 提交于 2020-01-14 14:07:24

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/5704080/cannot-update-wpf-gui-while-using-unmanaged-libraries-in-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!