C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#读写分离

C#实现读写分离的五种方法小结

作者:就是有点傻

在C#中实现分离功能通常指的是将不同的逻辑或责任分配到不同的类或组件中,以增强代码的可读性、可维护性和可扩展性,这通常涉及到设计模式、依赖注入和接口的使用,下面是一些在C#中实现分离功能的基本方法,需要的朋友可以参考下

1. 使用 ReaderWriterLockSlim

.NET 提供的高性能读写锁,支持以下模式:

using System.Threading;
 
public class ReadWriteExample
{
    private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
    private int _sharedData = 0;
 
    // 读操作
    public int ReadData()
    {
        _lock.EnterReadLock();
        try
        {
            return _sharedData;
        }
        finally
        {
            _lock.ExitReadLock();
        }
    }
 
    // 写操作
    public void WriteData(int value)
    {
        _lock.EnterWriteLock();
        try
        {
            _sharedData = value;
        }
        finally
        {
            _lock.ExitWriteLock();
        }
    }
}

优点

缺点

2. 使用 Concurrent 并发集合

.NET 的 System.Collections.Concurrent 命名空间提供了线程安全的集合类,内部已实现读写分离逻辑:

using System.Collections.Concurrent;
 
public class ConcurrentExample
{
    private readonly ConcurrentDictionary<string, int> _data = new();
 
    // 读操作(无锁)
    public int GetValue(string key)
    {
        return _data.TryGetValue(key, out int value) ? value : -1;
    }
 
    // 写操作(内部使用细粒度锁)
    public void UpdateValue(string key, int value)
    {
        _data.AddOrUpdate(key, value, (k, oldValue) => value);
    }
}

优点

缺点

3. 基于 volatile 和内存屏障(Memory Barrier)

适用于简单变量的读写分离,通过 volatile 关键字确保内存可见性:

public class VolatileExample
{
    private volatile bool _flag = false;
    private int _data = 0;
 
    // 读操作(无锁)
    public int ReadData()
    {
        if (_flag)
            return _data;
        return -1;
    }
 
    // 写操作(需要同步)
    public void WriteData(int value)
    {
        Interlocked.Exchange(ref _data, value); // 原子写入
        Volatile.Write(ref _flag, true);        // 确保写入对其他线程可见
    }
}

优点

缺点

4. 数据库读写分离

在数据库层面实现读写分离(如主从架构),C# 代码通过不同连接字符串路由请求:

public class DatabaseRouter
{
    private static readonly string ReadConnectionString = "Server=ReadServer;...";
    private static readonly string WriteConnectionString = "Server=WriteServer;...";
 
    public IDbConnection GetReadConnection() => 
        new SqlConnection(ReadConnectionString);
 
    public IDbConnection GetWriteConnection() => 
        new SqlConnection(WriteConnectionString);
}
 
// 使用示例
using (var readConn = DatabaseRouter.GetReadConnection())
{
    // 执行查询操作
}
 
using (var writeConn = DatabaseRouter.GetWriteConnection())
{
    // 执行更新操作
}

优点

缺点

5. 基于不可变数据(Immutable Data)

通过每次修改生成新对象实现无锁读取(如使用 ImmutableList<T> 或自定义不可变类型):

using System.Collections.Immutable;
 
public class ImmutableExample
{
    private ImmutableList<int> _data = ImmutableList<int>.Empty;
 
    // 读操作(无锁)
    public int GetItem(int index)
    {
        return _data[index];
    }
 
    // 写操作(原子替换)
    public void AddItem(int item)
    {
        ImmutableInterlocked.Update(ref _data, list => list.Add(item));
    }
}

优点

缺点

选择策略

场景推荐方案
细粒度代码级读写控制ReaderWriterLockSlim
高频并发集合操作ConcurrentDictionary 等并发集合
简单变量的读写volatile + Interlocked
数据库访问分离主从架构 + 连接路由
高频读、低频写不可变数据(如 ImmutableList

注意事项

到此这篇关于C#实现读写分离的五种方法小结的文章就介绍到这了,更多相关C#读写分离内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文