I am writing a multithreaded application where a thread locks the serialport and continuously sends commands and gets responses using SerialPort.Write(command) and SerialPort.ReadLine()
in a loop untill it gets an “OK” response for one particular command.
Is it possible for the thread to switch during a ReadLine() call and cause a TimeOutException.
I have a timeout set at 2000ms.
I have random TmeOutExceptions after the program runs for a few minutes (about 5 – 10)
23332 10:14:23 AM AutoLoader.WinS IRP_MJ_WRITE Serial0 SUCCESS Length 9: STG|4.5..
23336 10:14:23 AM AutoLoader.WinS IRP_MJ_READ Serial0 SUCCESS Length 1: O
23339 10:15:54 AM AutoLoader.WinS IRP_MJ_WRITE Serial0 SUCCESS Length 7: GTSNS..
23342 10:15:54 AM AutoLoader.WinS IRP_MJ_READ Serial0 SUCCESS Length 3: K..
23347 10:15:54 AM AutoLoader.WinS IRP_MJ_WRITE Serial0 SUCCESS Length 7: GLSTS..
23351 10:15:54 AM AutoLoader.WinS IRP_MJ_READ Serial0 SUCCESS Length 1: O
23355 10:15:54 AM AutoLoader.WinS IRP_MJ_READ Serial0 SUCCESS Length 3: K..
After 10:14:23 AM I get a TimeOutException which I suppressed.
while (response != "OK")
{
Thread.Sleep(1000);
_alComm.SendString("SSD|" + CurrentData.MeasuredDepthReturns + Environment.NewLine);
response = _alComm.ReceiveString(2000);
_alComm.SendString("STG|" + CurrentData.AvgGas + Environment.NewLine);
response = _alComm.ReceiveString(2000);
_alComm.SendString("GTSNS\r\n");
response = _alComm.ReceiveString(2000);
SetSamplingTimePercent(response);
}
and
public void SendString(string sDataToSend)
{
if (sDataToSend == "")
return;
try
{
AlPort.Write(sDataToSend);
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString(), "Error");
}
}
public string ReceiveString(int timeOut)
{
string inString = null;
try
{
// set read timeout
AlPort.ReadTimeout = timeOut;
inString = AlPort.ReadLine();
}
catch (TimeoutException ex)
{
return string.Empty;
}
return inString;
}
A
ReadLine(or any I/O for that matter) will cause a context-switch until it is serviced. Now, the way I see there are two possibilities: