AIGC标识 C# SerialPort 串口通信解决方案

Posted on 2026-10-19 11:17  不会写代码的  阅读(27)  评论(0)    收藏  举报
\# C# SerialPort 串口通信解决方案(Markdown)



>

> 适用场景:解决 SerialPort 粘包、丢包、死锁;采用 `BaseStream.ReadAsync` 异步循环读取方案,替代 DataReceived / ReadLine,工业级稳定方案。



```

\# C# SerialPort 异步串口通信解决方案(BaseStream.ReadAsync)

\## 概述

传统 `DataReceived + ReadLine` 写法三大痛点:

1\. \*\*粘包\*\*:串口是流式字节流,单次回调可能多条报文合并,或一条报文被拆分多次接收;

2\. \*\*丢包\*\*:DataReceived 回调处理耗时过长,串口硬件缓冲区溢出;

3\. \*\*死锁\*\*:DataReceived 后台线程 + UI 同步 Invoke + SerialPort.Close() 造成线程互锁,端口无法释放。



本方案:使用 `SerialPort.BaseStream.ReadAsync` 循环异步读取 + 环形字节缓冲区分包,\*\*彻底消除 DataReceived 死锁风险\*\*,自主完成帧解析,解决粘包问题;合理缓冲区设计降低丢包概率。



> 推荐运行环境:.NET 6 / .NET 7 / .NET 8;.NET Framework 的 BaseStream.ReadAsync 为伪异步,不推荐高波特率场景。



\## 核心设计思路

1\. 打开串口后启动独立异步读取循环,持续调用 `BaseStream.ReadAsync`;

2\. 读到的字节写入\*\*环形缓冲区\*\*(单生产者单消费者);

3\. 解析循环从环形缓冲区查找帧分隔符(文本协议:`\\r\\n`;二进制协议:帧头+长度)切分完整报文;

4\. 使用 `CancellationTokenSource` 安全取消异步读取循环,优雅关闭串口;

5\. UI 更新使用 `BeginInvoke`,禁止同步 Invoke,避免UI线程阻塞;

6\. 接收解析逻辑轻量化,复杂业务放入消息队列,防止阻塞接收链路。



\## 完整代码

\### 1. 异步串口助手类 SerialAsyncHelper.cs

```csharp

using System;

using System.IO.Ports;

using System.Threading;

using System.Threading.Tasks;



public class SerialAsyncHelper

{

  private readonly SerialPort \_port;
  private Task \_readTask;
  private CancellationTokenSource \_cts;
  private readonly CircularBuffer \_recvBuf;
  /// <summary>收到完整报文事件</summary>
  public event Action<byte\[]> OnFrameReceived;
  public SerialAsyncHelper(string comName, int baudRate, int recvBufferSize = 4096)
  {
      \_port = new SerialPort(comName, baudRate)
      {
          ReadBufferSize = recvBufferSize,
          WriteBufferSize = recvBufferSize
      };
      \_recvBuf = new CircularBuffer(recvBufferSize);
  }
  /// <summary>打开串口并启动异步读取循环</summary>
  public void Open()
  {
      if (\_port.IsOpen) return;
      \_port.Open();
      \_cts = new CancellationTokenSource();
      \_readTask = Task.Run(ReadLoopAsync, \_cts.Token);
  }
  /// <summary>异步读取主循环</summary>
  private async Task ReadLoopAsync()
  {
      var token = \_cts.Token;
      byte\[] readBuf = new byte\[1024];
      try
      {
          while (!token.IsCancellationRequested \&\& \_port.IsOpen)
          {
              // BaseStream.ReadAsync 异步读取
              int readLen = await \_port.BaseStream.ReadAsync(readBuf, 0, readBuf.Length, token);
              if (readLen <= 0) continue;
              // 写入环形缓冲区
              \_recvBuf.Write(readBuf, 0, readLen);
              // 分包解析,按\\r\\n分隔文本报文
              ParsePacket();
          }
      }
      catch (OperationCanceledException)
      {
          // 正常取消,无需报错
      }
      catch (IOException)
      {
          // 串口断开、拔插、端口关闭
      }
      catch (Exception ex)
      {
          // 全局异常捕获,可自定义日志输出
      }
  }
  /// <summary>分包解析:查找 \\r\\n(0x0D,0x0A) 分割报文,解决粘包</summary>
  private void ParsePacket()
  {
      while (true)
      {
          int index = \_recvBuf.IndexOfSequence(new byte\[] { 0x0D, 0x0A });
          if (index < 0) break;
          byte\[] frame = new byte\[index];
          \_recvBuf.Read(frame, 0, index);
          // 跳过分隔符\\r\\n
          \_recvBuf.Skip(2);
          OnFrameReceived?.Invoke(frame);
      }
  }
  /// <summary>安全关闭串口,等待读取任务退出</summary>
  public async Task CloseAsync()
  {
      if (\_cts != null)
      {
          \_cts.Cancel();
          if (\_readTask != null)
              await \_readTask;
          \_cts.Dispose();
      }
      if (\_port.IsOpen)
      {
          \_port.Close();
      }
  }

}

```



\### 2. 环形缓冲区 CircularBuffer.cs



```

/// <summary>单生产者单消费者环形字节缓冲区,处理串口流粘包</summary>

public class CircularBuffer

{

  private readonly byte\[] \_buffer;
  private int \_writeIndex;
  private int \_readIndex;
  public CircularBuffer(int capacity)
  {
      \_buffer = new byte\[capacity];
  }
  /// <summary>当前缓冲区可用字节数</summary>
  public int Available => \_writeIndex >= \_readIndex
      ? \_writeIndex - \_readIndex
      : \_buffer.Length - \_readIndex + \_writeIndex;
  /// <summary>写入数据到环形缓冲区</summary>
  public void Write(byte\[] data, int offset, int len)
  {
      for (int i = 0; i < len; i++)
      {
          \_buffer\[\_writeIndex] = data\[offset + i];
          \_writeIndex = (\_writeIndex + 1) % \_buffer.Length;
      }
  }
  /// <summary>读取指定长度数据</summary>
  public int Read(byte\[] dest, int offset, int len)
  {
      int readCount = Math.Min(len, Available);
      for (int i = 0; i < readCount; i++)
      {
          dest\[offset + i] = \_buffer\[\_readIndex];
          \_readIndex = (\_readIndex + 1) % \_buffer.Length;
      }
      return readCount;
  }
  /// <summary>跳过N个字节(用于跳过分隔符)</summary>
  public void Skip(int len)
  {
      len = Math.Min(len, Available);
      \_readIndex = (\_readIndex + len) % \_buffer.Length;
  }
  /// <summary>查找字节序列位置(查找\\r\\n)</summary>
  public int IndexOfSequence(byte\[] seq)
  {
      int avail = Available;
      for (int i = 0; i <= avail - seq.Length; i++)
      {
          bool match = true;
          for (int j = 0; j < seq.Length; j++)
          {
              byte b = GetByteAt((\_readIndex + i + j) % \_buffer.Length);
              if (b != seq\[j])
              {
                  match = false;
                  break;
              }
          }
          if (match) return i;
      }
      return -1;
  }
  private byte GetByteAt(int pos) => \_buffer\[pos];

}

```



\### 3. WinForm 使用示例



```

// 窗体加载

private SerialAsyncHelper \_serial;

private void Form1\_Load(object sender, EventArgs e)

{

&#x20;   \_serial = new SerialAsyncHelper("COM3", 115200, 4096);

&#x20;   \_serial.OnFrameReceived += (bytes) =>

&#x20;   {

&#x20;       string line = System.Text.Encoding.ASCII.GetString(bytes);

&#x20;       // 使用BeginInvoke更新UI,禁止同步Invoke

&#x20;       this.BeginInvoke(new Action(() =>

&#x20;       {

&#x20;           textBox1.AppendText(line + Environment.NewLine);

&#x20;       }));

&#x20;   };

}



// 打开串口按钮

private void btnOpen\_Click(object sender, EventArgs e)

{

&#x20;   \_serial.Open();

}



// 关闭串口按钮

private async void btnClose\_Click(object sender, EventArgs e)

{

&#x20;   await \_serial.CloseAsync();

}

```



\## 问题解决方案



\### ✅ 粘包解决



串口是字节流,不存在天然报文边界。



1\. 放弃单次读取等于一帧的假设;

2\. 使用环形缓冲区持续缓存数据流;

3\. 根据协议分隔符(`\\r\\n` / 帧头+长度)切割完整报文;>

> 二进制协议(Modbus):修改 `ParsePacket`,使用帧头+长度域解析,不要依赖换行符。



\### ✅ 丢包解决



1\. `ReadAsync` 异步IO,无 DataReceived 事件调度延迟;

2\. 增大串口读写缓冲区,高速通讯建议 4096\~8192;

3\. 接收解析逻辑轻量化,耗时业务放入独立队列;

4\. 超高波特率场景启用硬件流控 RTS/CTS;

5\. USB虚拟串口优先 CP2102,CH340驱动容易出现丢包。



\### ✅ 死锁解决



1\. 移除 DataReceived 事件,消除串口后台回调线程;

2\. 关闭流程:`CancellationTokenSource.Cancel()` → await 读取任务完成 → Close();

3\. UI更新统一使用 `BeginInvoke`,严禁同步 `Invoke`;

4\. 关闭时等待异步读取循环安全退出,再释放串口资源。



\## 避坑清单



1\. ❌ 禁止在 ReadLoopAsync 中执行耗时业务解析;

2\. ❌ 禁止同一 BaseStream 并发调用多个 ReadAsync;

3\. ❌ .NET Framework 慎用 BaseStream.ReadAsync,底层为伪异步;

4\. ❌ 不要混用同步 ReadLine、ReadExisting 和 BaseStream.ReadAsync;

5\. ✅ 取消令牌只能取消等待中的 ReadAsync,内存已读到的数据依然正常解析;

6\. ✅ 串口热拔插会抛出 IOException,需要捕获异常并做重连逻辑。



\## 扩展方向



1\. 增加异步发送队列(BaseStream.WriteAsync),实现全双工异步串口;

2\. 增加报文CRC校验;

3\. 增加串口自动重连;

4\. 二进制协议解析模板(帧头+长度+校验和);

5\. 日志记录,记录丢包、异常、收到报文。

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3