[英]SerialPort.Read not throwing TimeoutException
我有以下代碼
private SerialPort _port = null;
public SerialReader(string portname, int baudrate, Parity parity, int databits, StopBits stopbits, int readTimeoutMs = 10000)
{
//Set serial-port
_port = new SerialPort();
_port.PortName = portname;
_port.BaudRate = baudrate;
_port.Parity = parity;
_port.DataBits = databits;
_port.StopBits = stopbits;
_port.ReadTimeout = readTimeoutMs;
_port.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceivedNew);
_port.Open();
}
private void SerialPort_DataReceivedNew(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;
_buffer = new byte[port.BytesToRead];
try
{
port.Read(_buffer, 0, _buffer.Length);
}
catch (System.TimeoutException ex)
{
bool doDispose = true;
if (ReadTimeout != null)
ReadTimeout(ex, out doDispose);
if(doDispose)
this.Dispose();
return;
}
///////////
}
如果連接的設備發送的數據一切正常,但是如果我拔下數據,程序將永遠等待其他數據,而不會引發System.TimeoutException
( 文檔說應該拋出異常)。
我通過在bool doDispose = true;
上設置一個斷點來驗證這一點bool doDispose = true;
而且永遠都無法達到。
該程序集被編譯為“調試”。
這是錯誤還是我錯過了什么?
編輯
可能沒有調用SerialPort_DataReceivedNew,因為實際上沒有接收到任何數據,在這種情況下,如何捕獲錯誤?
編輯2
為了使其正常工作,我編輯了如下代碼:
添加的方法BeginGetData和PollSerialPort
public void BeginGetData()
{
_port.Open();
Thread pollingThread = new System.Threading.Thread(new System.Threading.ThreadStart(PollSerialPort));
pollingThread.Start();
}
private void PollSerialPort()
{
while (this.SerialPort_DataReceivedNew()) ;
}
並編輯了SerialPort_DataReceivedNew
private bool SerialPort_DataReceivedNew()
{
_buffer = new byte[_port.BytesToRead];
try
{
if (_port.Read(_buffer, 0, _buffer.Length) == 0)
_port.Write("\0");
}
catch (System.TimeoutException ex)
{
bool doDispose = true;
if (ReadTimeout != null)
ReadTimeout (this, out doDispose);
if (doDispose)
{
_port.Close();
return false;
}
return true;
}
///////////
}
在_port.Write("\\0");
我有TimeoutException
將斷點放到更早的位置,以查看是否曾經調用過DataReceived
。 即使是這樣,也沒有數據(很奇怪),您的緩沖區大小為零,因為BytesToRead
為零,所以它永遠不會超時。 嘗試改為在計時器事件中輪詢串行端口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.