is locking necessary for Dictionary lookup?

后端 未结 9 1903
太阳男子
太阳男子 2020-12-16 16:52
lock(dictionaryX)
{
   dictionaryX.TryGetValue(key, out value);
}

is locking necessary while doing lookups to a Dictionary ?

THe program is

9条回答
  •  太阳男子
    2020-12-16 17:35

    As mentioned 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.

    UPDATE: take a look at "Thread Safety" part of this page too.

提交回复
热议问题