Locking by string. Is this safe/sane?

前端 未结 9 1646
-上瘾入骨i
-上瘾入骨i 2020-12-14 01:33

I need to lock a section of code by string. Of course the following code is hideously unsafe:

lock(\"http://someurl\")
{
    //bla
}

So I\'

9条回答
  •  猫巷女王i
    2020-12-14 01:54

    This is how I implemented this locking schema:

    public class KeyLocker
    {
        private class KeyLock
        {
            public int Count;
        }
    
        private readonly Dictionary keyLocks = new Dictionary();
    
        public T ExecuteSynchronized(TKey key, Func function)
        {
            KeyLock keyLock =  null;
            try
            {              
                lock (keyLocks)
                {
                    if (!keyLocks.TryGetValue(key, out keyLock))
                    {
                        keyLock = new KeyLock();
                        keyLocks.Add(key, keyLock);
                    }
                    keyLock.Count++;
                }
                lock (keyLock)
                {
                    return function(key);
                }
            }
            finally
            {         
                lock (keyLocks)
                {
                    if (keyLock != null && --keyLock.Count == 0) keyLocks.Remove(key);
                }
            }
        }
    
        public void ExecuteSynchronized(TKey key, Action action)
        {
            this.ExecuteSynchronized(key, k =>
            {
                action(k);
                return true;
            });
        }
    }
    

    And used like this:

    private locker = new KeyLocker();
    ......
    
    void UseLocker()
    {
         locker.ExecuteSynchronized("some string", () => DoSomething());
    }
    

提交回复
热议问题