Using lock on the key of a Dictionary

后端 未结 7 1053
被撕碎了的回忆
被撕碎了的回忆 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:18

    Just came across this and thought id share some code I wrote a few years ago where I needed to a dictionary on a key basis

     using (var lockObject = new Lock(hashedCacheID))
     {
        var lockedKey = lockObject.GetLock();
        //now do something with the dictionary
     }
    

    the lock class

    class Lock : IDisposable
        {
            private static readonly Dictionary Lockedkeys = new Dictionary();
    
            private static readonly object CritialLock = new object();
    
            private readonly string _key;
            private bool _isLocked;
    
            public Lock(string key)
            {
                _key = key;
    
                lock (CritialLock)
                {
                    //if the dictionary doesnt contain the key add it
                    if (!Lockedkeys.ContainsKey(key))
                    {
                        Lockedkeys.Add(key, String.Copy(key)); //enusre that the two objects have different references
                    }
                }
            }
    
            public string GetLock()
            {
                var key = Lockedkeys[_key];
    
                if (!_isLocked)
                {
                    Monitor.Enter(key);
                }
                _isLocked = true;
    
                return key;
            }
    
            public void Dispose()
            {
                var key = Lockedkeys[_key];
    
                if (_isLocked)
                {
                    Monitor.Exit(key);
                }
                _isLocked = false;
            }
        }
    

提交回复
热议问题