is locking necessary for Dictionary lookup?

后端 未结 9 1902
太阳男子
太阳男子 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:11

    Yes you need to lock the dictionary for access in a multithreaded environment. The writing to a dictionary is not atomic, so it could add the key, but not the value. In that case when you access it, you could get an exception.

提交回复
热议问题