前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#线程同步ReaderWriterLockSlim

C#线程同步ReaderWriterLockSlim

作者头像
MaybeHC
发布2024-04-23 19:08:13
680
发布2024-04-23 19:08:13
举报
文章被收录于专栏:技术之路技术之路

ReaderWriterLockSlim可以将读锁和写锁进行分离,读锁允许多线程读取数据,写锁在被释放前会阻塞了其他线程的所有操作。下面以一个读Dictionary数据作为示例

代码语言:javascript
复制
 static ReaderWriterLockSlim _rw = new ReaderWriterLockSlim();
        static Dictionary<int, int> _items = new Dictionary<int, int>();
        static void Read()
        {
            
            Console.WriteLine("Reading contents of a dictionary");
            while (true)
            {
                try
                {
                    _rw.EnterReadLock();
                    foreach(var key in _items.Keys)
                    {
                        Console.WriteLine("读内容:{0}---{1}", key,Thread.CurrentThread.Name);
                        Thread.Sleep(TimeSpan.FromSeconds(0.1));
                    }
                }
                finally
                {
              
                    _rw.ExitReadLock();
                }
            }
        }
        static void Write(string threadName)
        {
            while (true)
            {
                try
                {
                    int newKey = new Random().Next(250);
                    _rw.EnterUpgradeableReadLock();
                    if (!_items.ContainsKey(newKey))
                    {
                        try
                        {
                            _rw.EnterWriteLock();
                            _items[newKey] = 1;
                            Console.WriteLine("Now key {0} is added to a dictionary by a {1}", newKey, threadName) ;
                        }
                        finally
                        {
                            _rw.ExitWriteLock();
                        }
                        Thread.Sleep(TimeSpan.FromSeconds(0.1));
                    }
                }
                finally
                {
                    _rw.ExitUpgradeableReadLock();
                }
            }
        }
         static void Main(string[] args)
        {
            new Thread(Read) { IsBackground = true }.Start();
            new Thread(Read) { IsBackground = true }.Start();
            new Thread(() => Write("Thread 1")) { IsBackground = true }.Start();
           Thread.Sleep(TimeSpan.FromSeconds(30));
        }
在这里插入图片描述
在这里插入图片描述

上图是运行后的结果,截取了部分,可以看到可以支持多个读锁和单个写锁。

_rw.EnterReadLock()获取读锁_rw.EnterUpgradeableReadLock()获取写锁

本文参与?腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-04-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com