FirstStep FirstStep - 1 year ago 132
C# Question

Serial port communication throwing TimeoutException

Following up with Serial Port Communication solution I implemented the below design. My code uses

to communicate with a Serial Port Utility Application that is listening on
within the same machine, then sending back (manually I type a message and press a button)

In my main I do this:

MyClass MyObj = new MyClass();
var message = MyObj.SendThenRecieveDataViaSerialPort("Test");

And then in my class I have this:

private static SerialPort MainSerialPort { get; set; } = new SerialPort();
private static string _ReceivedMessage;
private Thread readThread = new Thread(() => ReadSerialPort(ref _ReceivedMessage));

public string SendThenRecieveDataViaSerialPort(string _Message)
MainSerialPort = new SerialPort("com8", 9600);
MainSerialPort.ReadTimeout = 5000;
MainSerialPort.WriteTimeout = 5000;
readThread.Start(); // 1

{ // 2
MainSerialPort.WriteLine(_Message); // 3
readThread.Join(); // 6 - Console pops and waits
catch (TimeoutException ex)
Console.WriteLine("Exception in SendThenreceive");

return _ReceivedMessage;

private static void ReadSerialPort(ref string _message)
{ // 4
_message= MainSerialPort.ReadLine(); // 5
catch (TimeoutException ex)
// 7 - when time outs

However, it is throwing an error at step 7 saying:

{"The operation has timed out."}

InnerException: null

Could you tell me where I am going wrong? Please and thanks.

Answer Source

ReadLine waits until it sees the SerialPort.NewLine string. If this doesn't arrive within SerialPort.ReadTimeout the TimeoutException is thrown. So don't miss to send the NewLine!

Here is an alternative version without NewLine.

byte[] data = new byte[1024];
int bytesRead = MainSerialPort.Read(data, 0, data.Length);
_message = Encoding.ASCII.GetString(data, 0, bytesRead);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download