is locking necessary for Dictionary lookup?

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

    Yes, you have to lock if you have multithreaded updates on that dictionary. Check this great post for details: “Thread safe” Dictionary(TKey,TValue)

    But since ConcurrentDictionary<> introduced you can use it either via .NET 4 or by using Rx in 3.5 (it contains System.Threading.dll with implementation for new thread-safe collections)

提交回复
热议问题