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()获取写锁