首页 > 解决方案 > .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)
    {
        ...
    }
}

...

笔记

标签: c#.netserial-porttcpclient

解决方案


问题是这个标志 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.


推荐阅读