is locking necessary for Dictionary lookup?

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

    As with many subtle questions in programming, the answer is: Not necessarily.

    If you only add values as an initialization, then the subsequent reading does not need to be synchronized. But, on the other hand, if you're going to be reading and writing at all times, then absolutely you need to protect that resource.

    However, a full-blown lock may not be the best way, depending on the amount of traffic your Dictionary gets. Try a ReaderWriterLockSlim if you are using .NET 3.5 or greater.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题