SerialPort timeouts in ReadChar() method, WPF, "The operation has timed out."

24 Views Asked by At

Goal of my program is to send data to the RS232 and read them in with a different function. I have a direct connection (wire) between the RS232 pin 2 and pin 3. I'm getting randomly occurring timeouts in WPF when I'm reading the serial port, but I receive the data and can print it.

Create a serial port and a delegate in my class.

        SerialPort _serialPort;
        `public delegate void ReceiveData(object sender);`

Create a SerialDataReceivedEventHandler after InitializeComponent() _serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort1_DataReceive);

Define method for event.

        private void SerialPort1_DataReceive(object sender, SerialDataReceivedEventArgs e)
        {

            Dispatcher.BeginInvoke(new ReceiveData(OutputDataToList), sender);
        }

Define method for the delegate.

        private void OutputDataToList(object sender)
        {
            SerialPort sp = (SerialPort)sender;
            _inChar = '1';
            while (_inChar != '\n')
            {
                try
                {
                    _inChar = (char)sp.ReadChar();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error while receiving the serial port. " + ex.Message);
                    break; 
                }
                if (_inChar != '\n')
                {
                    _inMessage += _inChar;
                }
            }
            if (_inMessage != "")
            {
                lstReads.Items.Add(_inMessage);
                lstReads.SelectedIndex = lstReads.Items.Count - 1;
            }
            _inMessage = "";
        }

In 70%-90% of the tests, the program works fine but sometimes, this error occurs:

enter image description here

I changed the timeout time. It gets better (but still happens sometimes) for shorter time but I don't understand why.

            _serialPort.ReadTimeout = 500;
            _serialPort.WriteTimeout = 500;
0

There are 0 best solutions below