端口在一段时间后冻结,数据不显示在文本框中

问题描述 投票:0回答:1

我正在编写一个Windows窗体程序,其中我通过连接到模拟输入板的两个传感器读取特定应用的温度和通量。我需要不断地读取这些值(每 1 秒)。问题是几分钟后程序似乎在文本框中冻结,并且文本框中的值冻结! 我首先尝试使用 System.threading.timer 和 System.timer,但后来我尝试定义新线程。有没有办法重置端口或某物? 这是代码:

 public void Form1_Shown(object sender, EventArgs e)
    {
        Thread mainThread = new Thread(new ThreadStart(changeflag));
        mainThread.Start();

        Thread checktempThread = new Thread(new ThreadStart(checkvalues));
        checktempThread.Start();

    }

  private void checkvalues()
    {
        while (true)
        {
            if (flag == true)
            {
                if (!serialPort.IsOpen)
                {
                    serialPort.Open();
                }

                // Read analog values from input registers starting at address 33
                ushort startAddress = 33;

                ushort numRegistersToRead = 2;

                // Modbus slave device ID 
                byte slaveId = 49;


                // Read analog values from the input registers
                ushort[] analogValues = master.ReadInputRegisters(slaveId, startAddress, numRegistersToRead);


                // Convert the ushort values to float and display them in the textboxes
                if (analogValues.Length >= 2)
                {
                    float temperatureValue = (float)analogValues[0];
                    float flussoValue = (float)(analogValues[1]);


                    if (InvokeRequired)
                    {
                        // We are not on the UI thread, so we need to use Invoke
                        Invoke(new Action(() => textBoxTemperatura.Text = temperatureValue.ToString()));
                        Invoke(new Action(() => textBoxFlusso.Text = flussoValue.ToString()));
                    }
                    else
                    {
                        // We are on the UI thread, so update the UI control directly
                        textBoxTemperatura.Text = temperatureValue.ToString();
                        textBoxFlusso.Text = flussoValue.ToString();
                    }
                }
                flag = false;
            }
        }
    }


 private void changeflag()
    {
        while (rc1 == null)
        {
            Thread.Sleep(1200);
            flag = true;
        
        }

    }

我尝试了计时器,无论是在 UI 中还是使用线程,但它似乎使问题变得更糟。

c# windows winforms serial-port modbus
1个回答
0
投票

我认为在这种情况下你不需要线程。如果您尝试每秒读取两个寄存器,它不会冻结您的用户界面。 我在长时间读取 Modbus 时遇到了同样的问题。我有 int 变量来增加每次读取(基本上是计数器),在达到指定值后,我将关闭端口并建立新连接。

© www.soinside.com 2019 - 2024. All rights reserved.