多线程场景下线程安全数据库批量写入缓存的最佳模式是什么?有无更优无锁方案?
问题背景与现有实现
- 业务场景:多线程并发调用数据库写入接口,为降低数据库请求压力,采用本地缓存暂存数据、固定周期批量落库的方式减少交互频次
- 当前实现逻辑:通过自定义锁机制保证缓存读写的线程安全,配套定时器触发批量写入流程
- 核心优化诉求:替代现有带锁实现,寻找无锁模式下的线程安全缓存设计方案,提升高并发下的写入性能
现有实现代码如下(修正原代码的HTML转义问题):
public class WriteToDatabase : IWriter, IDisposable { public WriteToDatabase(PLCProtocolServiceConfig currentConfig) { writeTimer = new System.Threading.Timer(Writer); writeTimer.Change((int)currentConfig.WriteToDatabaseTimer.TotalMilliseconds, Timeout.Infinite); this.currentConfig = currentConfig; } private System.Threading.Timer writeTimer; private List<PlcProtocolDTO> writeCache = new List<PlcProtocolDTO>(); private readonly PLCProtocolServiceConfig currentConfig; private bool disposed; public void Write(PlcProtocolDTO row) { lock (this) { writeCache.Add(row); } } private void Writer(object state) { List<PlcProtocolDTO> oldCache = null; lock (this) { if (writeCache.Count > 0) { oldCache = writeChache; writeChache = new List<PlcProtocolDTO>(); } } if (oldCachce != null) { using (var s = VisuDL.CreateSession()) { s.Insert(oldCache); } } if (!this.disposed) writeTimer.Change((int)currentConfig.WriteToDatabaseTimer.TotalMilliseconds, Timeout.Infinite); } public void Dispose() { this.disposed = true; writeTimer.Dispose(); Writer(null); } }
现有实现的核心问题
- 锁性能损耗高:
lock(this)的锁粒度覆盖了所有写入路径和定时消费路径,高并发场景下会造成大量线程排队抢锁,吞吐量上不去 - 存在编译级bug:代码内变量名拼写错误(
writeChache、oldCachce与实际定义的writeCache不匹配),无法正常编译运行 - 无内存保护机制:缓存没有容量上限,如果数据库写入速度跟不上上游写入速度,缓存会无限膨胀最终撑爆内存
- 异常兜底缺失:批量落库失败时,已经从缓存中取出的批次数据会直接丢失;Dispose流程调用落库逻辑也没有异常捕获,容易在服务关闭时抛异常
- 锁对象设计不规范:直接锁公开的
this对象,容易被外部代码无意持锁造成死锁
可落地的无锁/低锁优化方案
方案1:极小改动量的ConcurrentQueue替换方案
如果不想大改原有逻辑,直接将带锁的List替换为.NET内置的无锁并发队列ConcurrentQueue即可,完全不需要手写锁,并发性能提升一个量级:
- 写入路径:多线程调用
Enqueue方法入队,内部无锁保证线程安全,没有锁排队开销 - 消费路径:定时触发时直接循环出队所有待处理数据,组成批次写入数据库
改造后的核心代码片段:
// 替换原有带锁的List定义 private readonly ConcurrentQueue<PlcProtocolDTO> _writeCache = new ConcurrentQueue<PlcProtocolDTO>(); // 定义私有锁对象(如果后续需要加锁场景) private readonly object _lockObj = new object(); public void Write(PlcProtocolDTO row) { // 完全无锁的入队操作 _writeCache.Enqueue(row); } private void Writer(object state) { var batch = new List<PlcProtocolDTO>(); // 一次性取出所有暂存数据 while (_writeCache.TryDequeue(out var item)) { batch.Add(item); // 可自定义单批次最大条数,避免单次写库压力过大 if (batch.Count >= 1000) break; } if (batch.Count > 0) { try { using var s = VisuDL.CreateSession(); s.Insert(batch); } catch (Exception) { // 失败数据重新塞回队列,避免丢失 foreach (var item in batch) { _writeCache.Enqueue(item); } } } if (!disposed) { writeTimer.Change((int)currentConfig.WriteToDatabaseTimer.TotalMilliseconds, Timeout.Infinite); } }
方案2:高性能生产消费场景推荐的Channel方案
如果项目使用.NET Core 3.0及以上版本,优先用官方提供的System.Threading.Channels实现无锁通道,这是目前生产消费场景下性能最高的实现方式,比ConcurrentQueue还有30%左右的性能提升,且内置容量控制能力:
- 可直接设置通道最大容量,超过容量时自定义处理策略(等待、丢弃、阻塞),从根源上避免内存溢出
- 可明确指定单消费者、多生产者的模型,内部实现会自动做无锁优化
- 内置批量读取、写入的扩展方法,不需要手动循环读写
完整改造后的代码示例:
public class WriteToDatabase : IWriter, IDisposable { // 创建有界无锁通道,最大缓存10000条数据,防止内存溢出 private readonly Channel<PlcProtocolDTO> _writeChannel = Channel.CreateBounded<PlcProtocolDTO>( new BoundedChannelOptions(10000) { FullMode = BoundedChannelFullMode.Wait, // 通道满时让写入端短暂等待,不丢数据 SingleReader = true, // 明确只有一个消费线程,启用内部无锁优化 SingleWriter = false // 允许多个线程并发写入 }); private readonly System.Threading.Timer _writeTimer; private readonly PLCProtocolServiceConfig _currentConfig; private readonly CancellationTokenSource _cts = new CancellationTokenSource(); public WriteToDatabase(PLCProtocolServiceConfig currentConfig) { _currentConfig = currentConfig; _writeTimer = new System.Threading.Timer(OnBatchWrite, null, TimeSpan.FromMilliseconds(currentConfig.WriteToDatabaseTimer.TotalMilliseconds), Timeout.InfiniteTimeSpan); } // 多线程写入方法,全程无锁 public void Write(PlcProtocolDTO row) { _writeChannel.Writer.TryWrite(row); } private void OnBatchWrite(object state) { if (_cts.IsCancellationRequested) return; var batch = new List<PlcProtocolDTO>(); // 一次性读取通道内所有暂存数据 while (_writeChannel.Reader.TryRead(out var item)) { batch.Add(item); if (batch.Count >= 1000) break; // 单批次最多1000条,避免拖垮数据库 } if (batch.Count > 0) { try { using var s = VisuDL.CreateSession(); s.Insert(batch); } catch (Exception) { // 失败数据重新写回通道,支持后续重试 _writeChannel.Writer.WriteAll(batch); } } if (!_cts.IsCancellationRequested) { _writeTimer.Change(TimeSpan.FromMilliseconds(_currentConfig.WriteToDatabaseTimer.TotalMilliseconds), Timeout.InfiniteTimeSpan); } } public void Dispose() { _cts.Cancel(); _writeTimer.Dispose(); // 消费完通道内剩余数据,服务关闭时不丢数据 _writeChannel.Writer.Complete(); var pendingBatch = _writeChannel.Reader.ReadAllAsync().ToEnumerable().ToList(); if (pendingBatch.Count > 0) { using var s = VisuDL.CreateSession(); s.Insert(pendingBatch); } _cts.Dispose(); } }
方案选型建议
- 如果是老框架项目(.NET Framework),优先选ConcurrentQueue方案,改动量最小,性能提升明显
- 如果是新开发项目,优先选Channel方案,性能最优,自带容量保护和异常兜底能力,长期维护成本最低
- 无论选哪种方案,都要避免直接锁
this的写法,锁对象要定义为私有只读字段,防止外部干扰
内容的提问来源于stack exchange,提问作者user1237393
相关产品推荐
相关产品推荐

