Is this non-locked TryGetValue() dictionary access thread-safe?

前端 未结 3 803
囚心锁ツ
囚心锁ツ 2020-12-31 07:14
private object lockObj = new object();

private Dictionary dict = new Dictionary();

public string GetOrAddFromDict(int key)
{
         


        
相关标签:
3条回答
  • 2020-12-31 07:44

    Question a: Is it thread-safe? If yes, why?

    Not only is it not thread safe; it will also throw with NullReferenceException if accessed while another thread is reorganizing the hash buckets. The lock statement is wicked fast, don't avoid it.

    Question b: How is this double-TryGetValue() pattern called?

    It's called a 'bug' by most people ;)

    0 讨论(0)
  • 2020-12-31 07:58

    Sadly, no.

    I carry around a custom HashMap that has this property.

    The defect is in the rehash() function.

    0 讨论(0)
  • 2020-12-31 08:07

    a) This is not thread-safe, as the underlying Dictionary itself is not thread safe. If another thread is calling Add at the same time, undefined behavior can occur.

    b) This is effectively an attempt at double-checked locking.

    I would recommend using the ConcurrentDictionary class instead, as it's designed for this scenario. Another option would be to use a ReaderWriterLockSlim (or ReaderWriterLock), if you're not targetting .NET 4.0.

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