WPF和跨线程操作 [英] WPF and cross thread operations

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

问题描述

我有一个小型WPF应用程序,我在其中模拟由传感器检测到的运动.我认为运动发生在1分钟后,然后在2分钟后停止.下面是我的代码:

I have a small WPF application where I'm simulating movement which is detected by a sensor. I fake that movement occurs after 1 minute and it stops after 2 minutes. Below is my code:

 public event Action OnMotionDetected;
        public event Action OnMotionReset;
        private DateTime startTime = DateTime.Now;

        public MotionDetectionService()
        {
            startTime = DateTime.Now;
            System.Threading.Thread mockThread = new System.Threading.Thread(new System.Threading.ThreadStart(StartMock));
            mockThread.Start();
        }

     private void StartMock()
            {
                while (DateTime.Now < startTime.AddMinutes(1))
                {
                    System.Threading.Thread.Sleep(1000);
                    Console.WriteLine("Remaining: " + (startTime.AddMinutes(1) - DateTime.Now).ToString());
                }
                FireMoveEvent();
                while (DateTime.Now < startTime.AddMinutes(2))
                {
                    System.Threading.Thread.Sleep(1000);
                    Console.WriteLine("Remaining: " + (startTime.AddMinutes(2) - DateTime.Now).ToString());
                }
                FireMoveEvent();
            }

            private void FireMoveEvent()
            {
                if(OnMotionDetected != null)
                {
                    OnMotionDetected();
                }
            }

            private void FireResetEvent()
            {
                if (OnMotionReset != null)
                {
                    OnMotionReset();
                }
            }

当线程触发事件时,我的UI会更新,但它说它无法更新,因为UI元素是在另一个线程上生成的.

When the thread fires the event my UI updates, but it says that it cannot update because the UI elements was generated on another thread.

关于如何解决的任何想法?

Any ideas on how to solve?

推荐答案

您可以使用Dispatcher.Invoke()编组到UI线程上.

You can use Dispatcher.Invoke() to marshall onto the UI thread.

请参阅:确保在MVVM WPF应用程序的UI线程上调用OnPropertyChanged()

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

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