Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serial data receive makes the application freeze

Tags:

c#

I am working on a Windows form application, where I send data through buttons, and continuously receive data for updating some gauge values.

The trouble I am facing, is when reading the serial port, if data is coming too fast, my application responds very slow, for example I can have a data rate of 1000Hz when reading.

I have attached a simplified version of my code.

What could cause this application to hang? I read that I need some separate thread? But how to achieve this?

namespace Motor
{
    public partial class Form1 : Form
    {
        SerialPort ComPort = new SerialPort();
        string InputData = String.Empty;
        delegate void SetTextCallback(string text);

        public Form1()
        {
            InitializeComponent();
            ComPort.DataReceived += 
                new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
        }

        private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
        {
            InputData = ComPort.ReadExisting();
            if (InputData != String.Empty)
            {
                this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
            }
        }

        private void SetText(string text)
        {
            if (text.Contains("CM")) 
            {
                // process the text content here
            }
        }
    }
}

1 Answers

This is most likely your issue

this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });

If your serial port is thrashing, its trying to marshal back to the UI thread all the time. Do you really need to update the main UI thread this fast? cant you just do it every second or periodically

In regards to the statement

What could cause this application to hang? I read that I need some separate thread? But how to achieve this?

SerialPort.DataReceived Event

The DataReceived event is raised on a secondary thread when data is received from the SerialPort object

I.e it is already running on secondary thread, so starting another thread is not going to help you

Update

In reference to your comment

1000hz is the data rate coming from the hardware, its no need for the GUI to be that fast, but i want the gauges to move smooth.

You can still make them smooth, still at least preventing UI throttling would be your key, try buffering for 200-300 milliseconds or so. I.e just play around with it

like image 85
TheGeneral Avatar answered Nov 29 '25 21:11

TheGeneral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!