System.IO.Ports.SerialPort and Multithreading

后端 未结 4 679
清酒与你
清酒与你 2021-02-02 04:42

I have some SerialPort code that constantly needs to read data from a serial interface (for example COM1). But this seems to be very CPU intensive and if the user moves the wind

4条回答
  •  不知归路
    2021-02-02 05:07

    You should rewrite port_DataReceived procedure to read data until port.BytesToRead is greater then zero, like this:

    private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
            var port = (SerialPort)sender;
            while (port.BytesToRead > 0)
            {
                int byte_count = port.BytesToRead;
                byte[] buffer = new byte[byte_count];
    
                int read_count = port.Read(buffer, 0, byte_count);
    
                // PROCESS DATA HERE
    
            }
    }
    

    Also I would recommend you to just insert data in queue list in procedure port_DataReceived, and perform data processing in separate thread.

提交回复
热议问题