Following up with Serial Port Communication solution I implemented the below design. My code uses com8
to communicate with a Serial Port Utility Application that is listening on com9
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;
MainSerialPort.Open();
readThread.Start(); // 1
try
{ // 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)
{
try
{ // 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.