Using lock on the key of a Dictionary

后端 未结 7 1051
被撕碎了的回忆
被撕碎了的回忆 2021-02-15 17:18

I have a Dictionary.

EDIT: It was pointed out to me, that my example was bad. My whole intention was not to update the references

7条回答
  •  -上瘾入骨i
    2021-02-15 18:01

    If I'm not mistaken, the original intention was to lock on a single element, rather than locking the whole dictionary (like table-level lock vs. row level lock in a DB)

    you can't lock on the dictionary's key as many here explained.

    What you can do, is to keep an internal dictionary of lock objects, that corresponds to the actual dictionary. So when you'd want to write to YourDictionary[Key1], you'll first lock on InternalLocksDictionary[Key1] - so only a single thread will write to YourDictionary.

    a (not too clean) example can be found here.

提交回复
热议问题