我有以下代码
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
(documentation说它应该抛出异常)。
我通过在bool doDispose = true;
上放置断点来验证这一点,但从未到达。
程序集编译为" Debug"。
这是一个错误还是我错过了什么?
修改
有可能没有调用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