Search code examples
c#.netserial-porttcpclient

.NET SerialPort is blocked when connected to socket


I have a problem with the SerialPort class in .NET.

When connecting to it with the below code, it works as expected. But if I connect to TCP/IP device via a TcpClient object at the same time, then the SerialPort.DataReceived never fires?

Below is an example of the code I use.

...

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)
    {
        ...
    }
}

...

NOTE

  • No exceptions are thrown at any time.

  • When the TcpClient is not connected the DataReceived event is triggered, but when the TcpClient is connected the event is not triggered.


Solution

  • The problem was that this flag this.isrunning is set by the TcpClient code when it is connected. If this takes too long, the SerialPort.DataReceived stops triggering.

    The solution was to modify the code with a call to 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.