AIGC标识 C# SerialPort 全双工异步串口通信方案

Posted on 2026-10-19 11:20  不会写代码的  阅读(22)  评论(0)    收藏  举报
```
# C# SerialPort 全双工异步串口通信方案
## 简介
基于 `SerialPort.BaseStream.ReadAsync` / `BaseStream.WriteAsync`
- 接收:异步循环读取 + 环形缓冲区,解决 **粘包、丢包**
- 发送:**异步发送队列 + 发送超时机制**,防止发送卡死
- 无 DataReceived 事件,根除经典 **DataReceived+Invoke+Close** 死锁问题
- 适用:.NET6/.NET7/.NET8;不推荐 .NET Framework(BaseStream异步兼容性差)

> 包含:环形缓冲区、异步接收循环、发送任务队列、发送超时、优雅关闭。

## 核心设计
1. **接收侧**:ReadAsync 持续读字节,写入环形缓冲区,按协议分割完整报文(示例:`\r\n`文本协议)
2. **发送侧**:线程安全消息队列,后台单独发送Task;每次取一条,调用 WriteAsync + CancellationToken 实现发送超时
3. **关闭流程**:CancellationTokenSource 取消读写任务 → 等待读写任务全部完成 → Close串口
4. **UI更新**:使用 BeginInvoke,禁止同步 Invoke

---

## 完整代码

### 1. SerialFullDuplexHelper.cs(主类:接收+发送队列)
```csharp
using System;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Concurrent;

public class SerialFullDuplexHelper
{
    private readonly SerialPort _port;

    // 接收
    private Task _readTask;
    private CancellationTokenSource _ctsRead;
    private readonly CircularBuffer _recvBuf;
    public event Action<byte[]> OnFrameReceived;

    // 发送队列
    private readonly ConcurrentQueue<SendItem> _sendQueue = new ConcurrentQueue<SendItem>();
    private Task _sendTask;
    private CancellationTokenSource _ctsSend;
    private readonly int _sendTimeoutMs;

    /// <summary>发送项封装,携带数据+超时</summary>
    private class SendItem
    {
        public byte[] Data { get; set; }
        public int TimeoutMs { get; set; }
        public TaskCompletionSource<bool> Tcs { get; set; }
    }

    /// <param name="comName">串口号</param>
    /// <param name="baudRate">波特率</param>
    /// <param name="recvBufferSize">接收环形缓冲区大小</param>
    /// <param name="defaultSendTimeoutMs">默认发送超时(ms)</param>
    public SerialFullDuplexHelper(string comName, int baudRate, int recvBufferSize = 4096, int defaultSendTimeoutMs = 1000)
    {
        _port = new SerialPort(comName, baudRate)
        {
            ReadBufferSize = recvBufferSize,
            WriteBufferSize = recvBufferSize
        };
        _recvBuf = new CircularBuffer(recvBufferSize);
        _sendTimeoutMs = defaultSendTimeoutMs;
    }

    #region 串口打开/关闭
    public void Open()
    {
        if (_port.IsOpen) return;
        _port.Open();

        // 启动接收任务
        _ctsRead = new CancellationTokenSource();
        _readTask = Task.Run(ReadLoopAsync, _ctsRead.Token);

        // 启动发送队列任务
        _ctsSend = new CancellationTokenSource();
        _sendTask = Task.Run(SendLoopAsync, _ctsSend.Token);
    }

    /// <summary>优雅关闭串口,等待读写任务全部退出</summary>
    public async Task CloseAsync()
    {
        // 停止发送队列
        if (_ctsSend != null)
        {
            _ctsSend.Cancel();
            if (_sendTask != null)
                await _sendTask;
            _ctsSend.Dispose();
        }

        // 停止接收循环
        if (_ctsRead != null)
        {
            _ctsRead.Cancel();
            if (_readTask != null)
                await _readTask;
            _ctsRead.Dispose();
        }

        if (_port.IsOpen)
            _port.Close();
    }
    #endregion

    #region 接收循环 ReadAsync
    private async Task ReadLoopAsync()
    {
        var token = _ctsRead.Token;
        byte[] readBuf = new byte[1024];
        try
        {
            while (!token.IsCancellationRequested && _port.IsOpen)
            {
                int readLen = await _port.BaseStream.ReadAsync(readBuf, 0, readBuf.Length, token);
                if (readLen <= 0) continue;

                _recvBuf.Write(readBuf, 0, readLen);
                ParsePacket();
            }
        }
        catch (OperationCanceledException)
        {
            // 正常取消
        }
        catch (IOException)
        {
            // 串口断开、拔端口
        }
        catch (Exception)
        {
            // 可增加日志
        }
    }

    /// <summary>分包解析:按 \r\n 分隔文本报文,解决粘包</summary>
    private void ParsePacket()
    {
        while (true)
        {
            int idx = _recvBuf.IndexOfSequence(new byte[] { 0x0D, 0x0A });
            if (idx < 0) break;

            byte[] frame = new byte[idx];
            _recvBuf.Read(frame, 0, idx);
            _recvBuf.Skip(2);
            OnFrameReceived?.Invoke(frame);
        }
    }
    #endregion

    #region 发送队列 WriteAsync
    /// <summary>入队发送,使用默认超时</summary>
    public Task<bool> SendAsync(byte[] data)
    {
        return SendAsync(data, _sendTimeoutMs);
    }

    /// <summary>入队发送,自定义超时</summary>
    public Task<bool> SendAsync(byte[] data, int timeoutMs)
    {
        var tcs = new TaskCompletionSource<bool>();
        var item = new SendItem
        {
            Data = data,
            TimeoutMs = timeoutMs,
            Tcs = tcs
        };
        _sendQueue.Enqueue(item);
        return tcs.Task;
    }

    private async Task SendLoopAsync()
    {
        var token = _ctsSend.Token;
        try
        {
            while (!token.IsCancellationRequested && _port.IsOpen)
            {
                if (_sendQueue.TryDequeue(out var sendItem))
                {
                    bool sendResult = await SendSinglePacketAsync(sendItem.Data, sendItem.TimeoutMs, token);
                    sendItem.Tcs.SetResult(sendResult);
                }
                else
                {
                    // 队列为空,短暂休眠,降低CPU占用
                    await Task.Delay(5, token);
                }
            }
        }
        catch (OperationCanceledException)
        {
            // 取消时,所有剩余队列标记失败
            while (_sendQueue.TryDequeue(out var item))
            {
                item.Tcs.SetResult(false);
            }
        }
        catch (Exception)
        {
            while (_sendQueue.TryDequeue(out var item))
            {
                item.Tcs.SetResult(false);
            }
        }
    }

    /// <summary>单次发送,带超时控制</summary>
    private async Task<bool> SendSinglePacketAsync(byte[] data, int timeoutMs, CancellationToken stopToken)
    {
        if (data == null || data.Length == 0 || !_port.IsOpen)
            return false;

        // 组合超时令牌 + 全局停止令牌
        using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(stopToken);
        timeoutCts.CancelAfter(timeoutMs);

        try
        {
            await _port.BaseStream.WriteAsync(data, 0, data.Length, timeoutCts.Token);
            await _port.BaseStream.FlushAsync(timeoutCts.Token);
            return true;
        }
        catch (OperationCanceledException)
        {
            // 超时 或者 串口关闭
            return false;
        }
        catch (IOException)
        {
            return false;
        }
        catch (Exception)
        {
            return false;
        }
    }
    #endregion
}
```

### 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];
    }

    public int Available => _writeIndex >= _readIndex
        ? _writeIndex - _readIndex
        : _buffer.Length - _readIndex + _writeIndex;

    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;
        }
    }

    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;
    }

    public void Skip(int len)
    {
        len = Math.Min(len, Available);
        _readIndex = (_readIndex + len) % _buffer.Length;
    }

    /// <summary>查找字节序列(查找\r\n 0x0D 0x0A)</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 SerialFullDuplexHelper _serial;

private void Form1_Load(object sender, EventArgs e)
{
    _serial = new SerialFullDuplexHelper("COM3", 115200, 4096, 1000);

    // 接收报文事件
    _serial.OnFrameReceived += (bytes) =>
    {
        string line = System.Text.Encoding.ASCII.GetString(bytes);
        this.BeginInvoke(new Action(() =>
        {
            textBox1.AppendText(line + Environment.NewLine);
        }));
    };
}

// 打开串口按钮
private void btnOpen_Click(object sender, EventArgs e)
{
    _serial.Open();
}

// 发送按钮,异步发送
private async void btnSend_Click(object sender, EventArgs e)
{
    byte[] sendData = System.Text.Encoding.ASCII.GetBytes("Hello World\r\n");
    bool ok = await _serial.SendAsync(sendData);
    if (ok)
    {
        textBoxSendLog.AppendText("发送成功\r\n");
    }
    else
    {
        textBoxSendLog.AppendText("发送失败/超时\r\n");
    }
}

// 关闭串口按钮
private async void btnClose_Click(object sender, EventArgs e)
{
    await _serial.CloseAsync();
}
```

---

## 方案要点说明

### ✅ 发送队列设计

1. 使用 `ConcurrentQueue` 线程安全:UI/其他线程可以随时调用 `SendAsync` 入队
2. 独立 `SendLoopAsync` 任务串行发送:**同一时刻只执行一次 WriteAsync**,禁止并发写流
3. `TaskCompletionSource`:调用方可以await发送结果,知道发送成功/超时失败
4. `CancellationTokenSource.CreateLinkedTokenSource`:同时监听【全局停止】+【单条发送超时】,防止 WriteAsync 卡死永久等待
5. `FlushAsync`:确保数据推送到底层串口流

### ✅ 粘包 / 丢包 / 死锁 解决方案

1. **粘包**:环形缓冲区缓存流式数据,按分隔符切割完整报文;不依赖单次ReadAsync等于一帧
2. **丢包**:异步读取循环,无DataReceived回调延迟;接收解析逻辑轻量化;高速场景加大缓冲区
3. **死锁**:移除DataReceived;关闭流程先取消读写任务,等待任务完成后Close;UI使用BeginInvoke

### ✅ 防卡死机制

- 每条发送自带超时,超时自动取消WriteAsync,不会无限阻塞
- 串口关闭时,队列中剩余待发送任务全部标记失败,不会挂起await
- 读写任务各自独立CancellationTokenSource,接收异常不影响发送,反之亦然

---

## 避坑清单

1. ❌ **禁止并行调用 BaseStream.WriteAsync**:队列保证串行发送,严禁外部直接调用WriteAsync
2. ❌ 不要混用同步 `Write` / `WriteLine` 和 BaseStream.WriteAsync
3. ❌ .NET Framework 不推荐使用,BaseStream异步为伪异步,超时机制不稳定
4. ❌ 发送回调更新UI依旧使用 BeginInvoke,不要用同步 Invoke
5. ✅ 发送队列会持续堆积,如果设备断连持续调用SendAsync,队列会暴涨;业务层增加队列长度判断,超过阈值拒绝入队
6. ✅ 二进制协议(Modbus)只需修改 `ParsePacket` 解析逻辑,改为帧头+长度解析,其余代码不用改动

---

## 扩展优化建议

1. 增加队列最大长度限制,防止断连时消息爆队列
2. 增加日志,记录发送成功/超时、接收报文、异常信息
3. 增加串口断线自动重连
4. 增加发送字节统计、接收字节统计
5. 二进制协议解析模板替换 `\r\n` 解析

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