我看到了一个.NET 3.5下的ConcurrentDictionary
实现(很抱歉我现在找不到链接),它使用了以下这种锁定方法:
var current = Thread.CurrentThread.ManagedThreadId;
while (Interlocked.CompareExchange(ref owner, current, 0) != current) { }
// PROCESS SOMETHING HERE
if (current != Interlocked.Exchange(ref owner, 0))
throw new UnauthorizedAccessException("Thread had access to cache even though it shouldn't have.");
传统的 lock
已经不再使用:
lock(lockObject)
{
// PROCESS SOMETHING HERE
}
问题是:这样做有任何真正的原因吗?它是否更快或具有某些隐藏的好处?
PS:我知道在一些最新版本的.NET中有一个ConcurrentDictionary,但我无法在遗留项目中使用。
编辑:
在我的特定情况下,我所做的只是以一种使其线程安全的方式操作内部的Dictionary类。
例如:
public bool RemoveItem(TKey key)
{
// open lock
var current = Thread.CurrentThread.ManagedThreadId;
while (Interlocked.CompareExchange(ref owner, current, 0) != current) { }
// real processing starts here (entries is a regular `Dictionary` class.
var found = entries.Remove(key);
// verify lock
if (current != Interlocked.Exchange(ref owner, 0))
throw new UnauthorizedAccessException("Thread had access to cache even though it shouldn't have.");
return found;
}
根据 @doctorlove 的建议,以下是代码:https://github.com/miensol/SimpleConfigSections/blob/master/SimpleConfigSections/Cache.cs