编辑:从我已经得到的答案中,我了解到我提出的第一个解决方案,并不是真正的“不阻塞读取”,因为只有一个线程可以进入可升级锁并且在读取释放之前不能获取写入锁......
所以我的问题是,如果不存在,如何以正确的方式使第一个解决方案成为“非阻塞读取”的创建?
我试图了解非阻塞多线程读取的两种解决方案。以下两种解决方案有什么区别(也许我仍然不明白一些事情,但我正在尝试):
/// <summary>
/// ReaderWriterLockSlim pattern
/// </summary>
public class ReadWriteLockCheck
{
Dictionary<string, object> _dict = new Dictionary<string, object>();
private ReaderWriterLockSlim _rwLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
public void CreateByKey(string key)
{
_rwLock.EnterReadLock();
try
{
if (!_dict.ContainsKey(key)) //Non blocking read - Check if exists
{
_rwLock.EnterWriteLock(); //Lock
try
{
_dict.Add(key, new object());
}
finally
{
_rwLock.ExitWriteLock();
}
}
}
finally
{
_rwLock.ExitReadLock();
}
}
public bool GetByKey(string key)
{
_rwLock.EnterWriteLock();
try
{
if (_dict.ContainsKey(key)) //Non blocking read
{
return true;
}
return false;
}
finally
{
_rwLock.ExitReadLock();
}
}
}
/// <summary>
/// Double check lock pattern
/// </summary>
public class MonitorLock
{
Dictionary<string, object> _dict = new Dictionary<string, object>();
private object _syncObj = new Object();
public void CreateByKey(string key)
{
if (!_dict.ContainsKey(key)) //Non blocking read - Check if exists
{
Monitor.Enter(_syncObj); //Lock
try
{
if (!_dict.ContainsKey(key)) //Check if between first check and lock someone already added
{
_dict.Add(key, new object());
}
}
finally
{
Monitor.Exit(_syncObj);
}
}
}
public bool GetByKey(string key)
{
if (_dict.ContainsKey(key)) //Non blocking read
{
return true;
}
return false;
}
}
在我看来,这两种解决方案都可以进行非阻塞读取,并且仅在写入时阻塞……如果是这样,有什么好处ReaderWriterLockSlim
?正如我在 google 中发现的那样,Monitor
它比ReaderWriterLockSlim
. 当然,我知道我在阅读时可能会得到不正确的字典状态,但这对我来说没关系。
谢谢