代码之家  ›  专栏  ›  技术社区  ›  smerlung

.NET SerialPort在连接到套接字时被阻止

  •  0
  • smerlung  · 技术社区  · 8 年前

    我对.NET中的SerialPort类有问题。

    下面是我使用的代码示例。

    ...
    
    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连接时,不会触发该事件。

    1 回复  |  直到 8 年前
        1
  •  0
  •   smerlung    8 年前

    问题是这面旗这个。正在运行连接时由TcpClient代码设置。如果时间太长SerialPort.DataReceived已接收停止触发。

    解决方案是通过调用this.SerialPort.DiscardInBuffer放弃()

        if(!this.isrunning)
        {
            this.SerialPort.DiscardInBuffer();
            return;
        }