is locking necessary for Dictionary lookup?

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

    Locking is only needed when you are synchronizing access to a resource between threads. As long as there are not mulitple threads involved then locking is not needed here.

    In the context of updating and reading the value from multiple threads, yes a lock is absolutely necessary. In fact if you're using 4.0 you should consider switching to one of the collections specifically designed for concurrent access.

提交回复
热议问题