如果我只是阅读字典,我应该锁定字典吗?
Should I Be Locking a Dictionary If I'm Only Reading From It?
我有一个存储字典的 class。一个线程可以在另一个函数中编辑这个字典。鉴于它正在写入这本字典,我确保它被锁在锁中。例如:
public void SetModuleLogLevel(string module, LogLevel logLevel)
{
if (module == "Other" || !this._moduleToLogLevel.ContainsKey(module))
return;
lock (this._lock)
{
this._moduleToLogLevel[module] = logLevel;
}
}
我有另一个函数 returns 来自这本字典的值。例如,
private bool IsUrgentToLog(string module, LogLevel logLevel)
{
if (!this._moduleToLogLevel.ContainsKey(module)) return false;
lock (this._lock)
{
if (this._moduleToLogLevel[module] < logLevel) return true;
}
return false;
}
考虑到我只是在这个函数中读取这个字典,它需要锁吗?
Dictionary<TKey, TValue>
在任何线程改变它时不做任何保证,即你可以有 "any number of readers" 或 "at most one writer, and zero readers"。所以:如果它 可以 发生突变:是的,你确实需要 lock
读取,以保护其他读者。
您可能会发现使用 ConcurrentDictionary<TKey, TValue>
(任意数量的读者 and/or 作者)更容易,或者如果您不介意丢失泛型:Hashtable
(最多一个作者与 任意数量的读者并发,即您只需要同步写入)。
我有一个存储字典的 class。一个线程可以在另一个函数中编辑这个字典。鉴于它正在写入这本字典,我确保它被锁在锁中。例如:
public void SetModuleLogLevel(string module, LogLevel logLevel)
{
if (module == "Other" || !this._moduleToLogLevel.ContainsKey(module))
return;
lock (this._lock)
{
this._moduleToLogLevel[module] = logLevel;
}
}
我有另一个函数 returns 来自这本字典的值。例如,
private bool IsUrgentToLog(string module, LogLevel logLevel)
{
if (!this._moduleToLogLevel.ContainsKey(module)) return false;
lock (this._lock)
{
if (this._moduleToLogLevel[module] < logLevel) return true;
}
return false;
}
考虑到我只是在这个函数中读取这个字典,它需要锁吗?
Dictionary<TKey, TValue>
在任何线程改变它时不做任何保证,即你可以有 "any number of readers" 或 "at most one writer, and zero readers"。所以:如果它 可以 发生突变:是的,你确实需要 lock
读取,以保护其他读者。
您可能会发现使用 ConcurrentDictionary<TKey, TValue>
(任意数量的读者 and/or 作者)更容易,或者如果您不介意丢失泛型:Hashtable
(最多一个作者与 任意数量的读者并发,即您只需要同步写入)。