2012-04-24 134 views
0

我正在編寫一個多線程應用程序,其中一個線程鎖定串口,並不斷髮送命令並獲取使用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; 
} 
+0

切換爲上下文切換? – Tudor 2012-04-24 15:46:27

+0

yes.a上下文切換。 – cheedep 2012-04-24 15:50:08

+0

你能發表一些代碼嗎? – 2012-04-24 16:05:03

回答

1

ReadLine(或就此而言的任何I/O)將導致一個上下文切換,直到它被服務。現在,我看到的方式有兩種可能性:

  1. 爲線程撐由操作系統掛起,直到超時且異常被拋出或
  2. 你留暫停,直到I/O是在其服務很有可能操作系統會立即喚醒您的線程並搶佔其他線程以允許您的代碼運行。請記住,任何現代操作系統都會對I/O綁定線程提供慷慨的優先級提升。
+0

我懷疑可能性1.我該怎麼做才能確認是否屬於這種情況,我該如何預防。 – cheedep 2012-04-24 16:36:48

+0

如果可能性1(這是超時可能發生的唯一情況),則表示串行端口響應時間過長。 – Tudor 2012-04-24 16:37:49