线程化串口查询并在ListView控件中使用结果 [英] Threading serial port query and using the result in a ListView control

查看:18
本文介绍了线程化串口查询并在ListView控件中使用结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设备,如果我在其中发送格式正确的字符串;我得到一个字符串.我想在 WPF ListView 控件中使用这个返回的字符串,但是我在无限查询串行端口另一端的设备时遇到了麻烦.我想每 3 秒左右刷新一次数据.
这是应用程序逻辑:

I have a device in which if I send a properly formatted string; I get a string back. I would like to use this returned string in a WPF ListView control but I'm having trouble infinitely querying the device on the other end of the serial port. I would like to refresh the data every 3 or so seconds.
Here is the application logic:

            public static void queryDevice()
        {
            SerialPort _serialPort = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);
            _serialPort.Handshake = Handshake.None;
            ObservableCollection<string> store= new ObservableCollection<string> { " ", " ", " " };
            string[] query = new string[3] { "t02", "t03", "t04" };
            while (true)
            {
                for (int i = 0; i < 3; i++)
                {
                    string add = SerialCom.returnData(query[i], _serialPort);//returns data depending on which query was sent
                    if (store[i] != add)
                    {
                        store.Add(add);
                    }
                }
                Thread.wait(300);

            }
        }

我正在尝试寻找线程化此代码的最佳方法,因为将此代码放入 UI 线程会锁定 UI 线程.我打算使用 ObservableCollection 作为该笔记上 ListView 的数据源.

I'm trying to find the best way to thread this code as putting this code in the UI thread locks the UI thread up. I am planning to use the ObservableCollection as the datasource for the ListView on that note.

谢谢!

推荐答案

在我看来,您应该将这些代码分成两种方法并使用线程..

You should separate those code into two methods and using threading in my opinion..

可能是这样

    public static void queryDevice()
    {
        SerialPort _serialPort = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);
        _serialPort.Handshake = Handshake.None;
        ObservableCollection<string> store= new ObservableCollection<string> { " ", " ", " " };
        string[] query = new string[3] { "t02", "t03", "t04" };
        Thread thread = new Thread(delegate(){Process(store,query,_serialPort);});
        thread.Start();
    }



     public static void Process(ObservableCollection<string> store, string[] query, SerialPort _serialPort)
     {
         while (true)
         {
             for (int i = 0; i < 3; i++)
             {
                 string add = SerialCom.returnData(query[i], _serialPort);
                 if (store[i] != add)
                 {
                     store.Add(add);
                 }
             }
             Thread.Sleep(300);
         }
     }

这篇关于线程化串口查询并在ListView控件中使用结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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