c# - .NET SerialPort 在连接到套接字时被阻止
问题描述
我对 .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 连接时未触发事件。
解决方案
问题是这个标志 this.isrunning 是由 TcpClient 代码在连接时设置的。如果这需要太长时间,SerialPort.DataReceived 将停止触发。
解决方案是通过调用 this.SerialPort.DiscardInBuffer() 来修改代码
if(!this.isrunning)
{
this.SerialPort.DiscardInBuffer();
return;
}
So I assume that there is some kind of buffer overflow happening somewhere, but I never get any exceptions, the event simply stops firing.
推荐阅读
- c++ - VSCode C/C++ 远程开发 - 语法高亮颜色不起作用
- python - 在 django/docker 环境中未读取环境变量
- terraform - 主用户在 RDS 中被删除会 terraform 删除并重新创建资源吗?
- elasticsearch - 如何使用 Logstash 和 grok 插件创建字段
- spring - 是否有现有方法可以从 Spring 应用程序上下文生成接线代码?
- javascript - 将 for 循环转换为 ES6 for of 循环
- rust - How to send bytes::bytes::Bytes by futures:stream::Stream?
- javascript - chart.js 雷达在值为 12 时显示 0
- javascript-objects - 如何防止 Object.keys() 排序?
- javascript - 无法对使用 HOOK 实现的未安装组件执行 React 状态更新