我正在編寫一個多線程應用程序,其中一個線程鎖定串口,並不斷髮送命令並獲取使用SerialPort.Write(command)和SerialPort.ReadLine() 的響應,直到它獲得「OK」響應一個特定的命令。serialport timeoutexception線程切換
在ReadLine()調用期間線程是否可能切換並導致TimeOutException。
我有超時設置在2000毫秒。
我有隨機TmeOutExceptions程序幾分鐘(約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..
後,上午10點14分23秒,我得到一個TimeoutException我抑制。
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);
}
和
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;
}
切換爲上下文切換? – Tudor 2012-04-24 15:46:27
yes.a上下文切換。 – cheedep 2012-04-24 15:50:08
你能發表一些代碼嗎? – 2012-04-24 16:05:03