Using lock on the key of a Dictionary

后端 未结 7 1045
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  情话喂你
    2021-02-15 18:06

    No, this would not work.

    The reason is string interning. This means that:

    string a = "Something";
    string b = "Something";
    

    are both the same object! Therefore, you should never lock on strings because if some other part of the program (e.g. another instance of this same object) also wants to lock on the same string, you could accidentally create lock contention where there is no need for it; possibly even a deadlock.

    Feel free to do this with non-strings, though. For best clarity, I make it a personal habit to always create a separate lock object:

    class Something
    {
        bool threadSafeBool = true;
        object threadSafeBoolLock = new object(); // Always lock this to use threadSafeBool
    }
    

    I recommend you do the same. Create a Dictionary with the lock objects for every matrix cell. Then, lock these objects when needed.

    PS. Changing the collection you are iterating over is not considered very nice. It will even throw an exception with most collection types. Try to refactor this - e.g. iterate over a list of keys, if it will always be constant, not the pairs.

提交回复
热议问题