lock(dictionaryX)
{
dictionaryX.TryGetValue(key, out value);
}
在查找字典时是否需要锁定?
该程序是多线程的,同时向字典添加键/值。字典被锁定。
最佳答案
如前所述here :
Using TryGetValue() without locking is not safe. The dictionary is temporarily in a state that makes it unsuitable for reading while another thread is writing the dictionary. A dictionary will reorganize itself from time to time as the number of entries it contains grows. When you read at the exact time this re-organization takes place, you'll run the risk of finding the wrong value for the key when the buckets got updated but not yet the value entries.
更新: 查看 this page 的“线程安全”部分也是。
关于c# - 字典查找是否需要锁定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4000347/