我SerialPort通过DataReceived活动打开并接收数据.
有没有办法检测是否SerialPort断开连接?
我尝试过ErrorReceived和PinChanged事件但没有运气.
除此之外,SerialPort.IsOpen在物理断开连接时返回true.
Mat*_*and 13
USB串口是一个巨大的痛苦.例如,请参阅此问题.我不确定它是否真的是用.NET 4.0修复的,但是当天我试图处理断开连接的问题,导致整个程序崩溃,如下所示:
public class SafeSerialPort : SerialPort
{
private Stream theBaseStream;
public SafeSerialPort(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
: base(portName, baudRate, parity, dataBits, stopBits)
{
}
public new void Open()
{
try
{
base.Open();
theBaseStream = BaseStream;
GC.SuppressFinalize(BaseStream);
}
catch
{
}
}
public new void Dispose()
{
Dispose(true);
}
protected override void Dispose(bool disposing)
{
if (disposing && (base.Container != null))
{
base.Container.Dispose();
}
try
{
if (theBaseStream.CanRead)
{
theBaseStream.Close();
GC.ReRegisterForFinalize(theBaseStream);
}
}
catch
{
// ignore exception - bug with USB - serial adapters.
}
base.Dispose(disposing);
}
}
Run Code Online (Sandbox Code Playgroud)
向我改编的人道歉,似乎我没有在我的代码中记下它.问题显然源于.NET在串口消失的情况下如何处理底层流.串口断开后,似乎无法关闭流.
我使用的另一个策略是创建一个只执行串行通信部分的小程序,并为我的主程序提供WCF服务以进行连接.这样,当USB串行适配器脱落并崩溃通信程序时,我可以自动从主程序重启它.
最后,我不知道为什么没有人销售锁定USB端口以避免整个意外断开问题,尤其是USB串口适配器!
| 归档时间: |
|
| 查看次数: |
21682 次 |
| 最近记录: |