从WPF中的另一个线程访问UI控件 [英] Access UI controls from another thread in WPF

查看:1099
本文介绍了从WPF中的另一个线程访问UI控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用网络摄像头拍摄图像。基于所使用的设备(笔记本电脑),图像捕获或者在某些时候冻结或者不冻结。我想要实现的是确保捕获不会冻结。



这是捕获图像的功能。它使用Direct Show Library

Hi, i am capturing image with Webcam. based on the device(laptop) used, the image capture either freezes at some point or not. What i want to achieve is to ensure that the capture does not freeze.

Here is the function that captures the image. it uses Direct Show Library

private void captureImage()
       {
           // Release any previous buffer
           if (m_ip != IntPtr.Zero)
           {
               Marshal.FreeCoTaskMem(m_ip);
               m_ip = IntPtr.Zero;
           }

           // capture image
           m_ip = cam.Click();
           b = new Bitmap(cam.Width, cam.Height, cam.Stride, System.Drawing.Imaging.PixelFormat.Format24bppRgb, m_ip);

           // If the image is upsidedown
           b.RotateFlip(RotateFlipType.RotateNoneFlipY);

           System.Windows.Controls.Image win = UIHelper.FindChild<System.Windows.Controls.Image>(System.Windows.Application.Current.MainWindow, "photo");

           win.Source = BitmapToImageSource(b);
           cam.Dispose();
           this.DialogResult = true;
           this.Close();
       }





我尝试过:



我正在尝试在调度程序计时器的Tick事件处理程序中实现异步操作





What I have tried:

i'm trying to implement the asynchronous operation in a the Tick event handler of a dispatcher timer

void timer_Tick(object sender, EventArgs e)
        {
            i = --i;
            count.Content = i;
            if (i == 2)
            {
                prog.IsActive = true;
                new Task(captureImage).Start();
                
            }
            if (i == 0)
            {
                timer.Stop();
            }
        }





当我这样做时,我收到此错误调用线程无法访问此对象因为另一个线程拥有它在这一行



when i do that, i get this error "The calling thread cannot access this object because a different thread owns it" on this line "

System.Windows.Controls.Image win = UIHelper.FindChild<System.Windows.Controls.Image>(System.Windows.Application.Current.MainWindow, "photo");

在捕获函数中



但当我使用dispatcher.Invoke时这样

" in the capture function

but when i use a dispatcher.Invoke like this

this.Dispatcher.Invoke((Action)(() =>
                {
                    captureImage();
                }));



框架仍然冻结,任何想法如何解决这个问题?


the frame still freezes, any idea how to fix this?

推荐答案

了解MVVM的基础知识。将某些控件(View)的属性绑定到ViewModel的属性。绑定引擎负责正确的线程。在你的模型中,运行你的线程来捕获图像,为每个新图像向ViewModel引发一个事件。
Learn the basics of MVVM. Bind properties of some controls (View) to properties of a ViewModel. The Binding engine takes care of the correct thread. In your model, run your thread for capturing the image, raise an event to the ViewModel for every new image.


这篇关于从WPF中的另一个线程访问UI控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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