单例模式使用读写锁并发访问SQLite的完整代码

 SQLite数据库+单例模式+读写锁+SqlSugarScope

实体类
// Models/LogEntity.cs
namespace SqlSugarSafeDemo.Models
{
    public class LogEntity
    {
        public int Id { get; set; }
        public string Message { get; set; }
        public DateTime CreatedAt { get; set; } = DateTime.Now;
    }
}
核心类
using SqlSugar;
using System.Threading;

namespace SqlSugarSafeDemo
{
    /// <summary>
    /// SqlSugarScope 单例 + 读写锁 工具类
    /// 保证全局唯一数据库访问 + 线程安全读写
    /// </summary>
    public sealed class SqlSugarSafeHelper
    {
        // 🔒 单例(线程安全 Lazy 初始化)
        private static readonly Lazy<SqlSugarSafeHelper> _instance =
            new Lazy<SqlSugarSafeHelper>(() => new SqlSugarSafeHelper());

        public static SqlSugarSafeHelper Instance => _instance.Value;//外部调用直接使用Instance

        // 🔗 SqlSugarScope 对象(操作 SQLite 的核心)
        private readonly SqlSugarScope _db;

        // 🔄 读写锁,控制并发安全
        private readonly ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim();

        // 私有构造函数
        private SqlSugarSafeHelper()
        {
            // 初始化 SqlSugarScope(SQLite)
            _db = new SqlSugarScope(new SqlSugar.ConnectionConfig
            {
                ConnectionString = "Data Source=./appdata.db;Version=3;",
                DbType = SqlSugar.DbType.Sqlite,
                IsAutoCloseConnection = true // 推荐
            }, db =>
            {
                // 如果表不存在,自动创建(CodeFirst)
                db.CodeFirst.InitTables<LogEntity>();
            });
        }

        /// <summary>
        /// 执行写操作(增删改,加写锁 + 事务)
        /// </summary>
        public void ExecuteWriteWithLock(Action<SqlSugarScope> writeAction)
        {
            _rwLock.EnterWriteLock(); // 写锁:独占
            try
            {
                //这里使用了事务
                _db.Ado.UseTran(() =>
                {
                    writeAction(_db); // 如:插入、更新、删除
                });
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[写入失败] {ex.Message}");
                throw;
            }
            finally
            {
                _rwLock.ExitWriteLock();
            }
        }

        /// <summary>
        /// 执行读操作(查询,加读锁)
        /// </summary>
        public T QueryWithLock<T>(Func<SqlSugarScope, T> queryAction)
        {
            _rwLock.EnterReadLock(); // 读锁:共享
            try
            {
                return queryAction(_db);
            }
            finally
            {
                _rwLock.ExitReadLock();
            }
        }

        /// <summary>
        /// 示例:插入日志(内部使用写锁)
        /// </summary>
        public void InsertLog(string message)
        {
            ExecuteWriteWithLock(db =>
            {
                db.Insertable(new LogEntity { Message = message }).ExecuteCommand();
            });
        }

        /// <summary>
        /// 示例:查询所有日志(内部使用读锁)
        /// </summary>
        public System.Collections.Generic.List<LogEntity> GetAllLogs()
        {
            return QueryWithLock(db =>
            {
                return db.Queryable<LogEntity>()
                        .OrderByDescending(x => x.CreatedAt)
                        .Take(10)
                        .ToList();
            });
        }
    }
}
使用类
using System;
using System.Threading;
using SqlSugarSafeDemo.Models;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("🚀 SqlSugarScope + 单例 + 读写锁 示例启动");

        // 模拟:一个线程定时写入,一个线程定时读取
        var writerThread = new Thread(() =>
        {
            for (int i = 0; i < 5; i++)
            {
                string msg = $"日志-{i} {DateTime.Now:HH:mm:ss.fff}";
                SqlSugarSafeHelper.Instance.InsertLog(msg);
                Console.WriteLine($"✅ [写入] {msg}");
                Thread.Sleep(1000); // 每秒写一条
            }
        });

        var readerThread = new Thread(() =>
        {
            for (int i = 0; i < 3; i++)
            {
                var logs = SqlSugarSafeHelper.Instance.GetAllLogs();
                Console.WriteLine("📥 [读取] 最新日志:");
                foreach (var log in logs.Take(3))
                {
                    Console.WriteLine($"  → ID:{log.Id}, Msg:{log.Message}, Time:{log.CreatedAt:HH:mm:ss.fff}");
                }
                Thread.Sleep(3000); // 每3秒读一次
            }
        });

        writerThread.Start();
        readerThread.Start();

        writerThread.Join();
        readerThread.Join();

        Console.WriteLine("🛑 程序结束");
    }
}
posted @ 2025-09-24 11:20  菜loulou  阅读(6)  评论(0)    收藏  举报