我对 .NET 中的 SerialPort 类有疑问。
使用以下代码连接到它时,它按预期工作。但是,如果我同时通过 TcpClient 对象连接到 TCP/IP 设备,那么 SerialPort.DataReceived 永远不会触发?
下面是我使用的代码示例。
...
public void Initialize()
{
try
{
this.SerialPort = new SerialPort(this.portname, this.baudrate, this.parity);
if (!this.SerialPort.IsOpen)
{
this.SerialPort.Open();
}
this.SerialPort.DataReceived += SerialPort_DataReceived;
}
catch (Exception ex)
{
...
}
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if(!this.isrunning)
{
return;
}
try
{
int count = this.SerialPort.Read(this.buffer, 0, this.buffer.Length);
var data = new byte[count];
Array.Copy(this.buffer, data, count);
this.binarywriter.Write(data);
}
catch (Exception ex)
{
...
}
}
...
笔记
任何时候都不会抛出异常。
当 TcpClient 未连接时触发 DataReceived 事件,但当 TcpClient 连接时未触发事件。