Dynamic Multi-threading lock with while loop I have already asked a question about a dynamic multi threaded lock, and the reviewer found a problem. 

Here is the description of the problem that I need to solve:


  I need to create a structure to control dynamically created locks. For example, I have 100 threads running, and each thread will "process" a "key". Sometimes two threads could be processing the same "key", and if that occurs, a dynamic lock needs to be created and used by both, so only one thread can process the key at a time.


I rewrote my code again with a new idea, and I would like you to review it for possible bugs/leaks caused by multithreaded processing.

//Implementation of the class who will block to two process don't execute if they have the same key.
public class DynamicLockGenerator
{
    private static Dictionary&lt;string, object&gt; _locksByKeys = new Dictionary&lt;string, object&gt;();

    private static object _lock = new object();

    public static void ExecuteLock(string key, Action action)
    {
        try
        {
            bool isFree = true;

            do
            {
                lock (_lock)
                {
                    if (!_locksByKeys.ContainsKey(key))
                        _locksByKeys.Add(key, new GuidLock(Guid.NewGuid()));

                    isFree = Monitor.TryEnter(_locksByKeys[key]);
                }

                if (!isFree)
                {
                    Thread.Sleep(50);
                }

            } while (!isFree);

            action.Invoke();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            Monitor.Exit(_locksByKeys[key]);
        }
    }
}



//This is the method call.
DynamicLockGenerator.ExecuteLock(key, () =&gt; SomeMethodToExecuteAlone());
Just one question : when do you release the key ?
Suppose twice the same key is called almost simultaneously, so that one of the two threads involved will go through the 


  Thread.Sleep(50) ;


line ..
The first thread enters the lock, the key is added to the dictionary, fine.
At almost the same time the other thread enters the lock, find the key already there and go sleeping.
When the first thread exit, if you don't release the key, the other thread will wait a long long time ..
May be something like  

_lockByKeys.Remove(key)


is enough to solve this one.

After this, reading again this code, I found a dictionary, a lock and a monitor. I'm quite sure that a ConcurrentDictionary could make the same job, with a cleaner code if not faster.

Lastly, 100 threads with some of them blocked could become a production nightmare if too much keys have the same value.

Hope this help !