1. 程式人生 > >C#執行緒同步ReaderWriterLockSlim

C#執行緒同步ReaderWriterLockSlim

ReaderWriterLockSlim可以將讀鎖和寫鎖進行分離,讀鎖允許多執行緒讀取資料,寫鎖在被釋放前會阻塞了其他執行緒的所有操作。下面以一個讀Dictionary資料作為示例

 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()獲取寫鎖