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<string, object> _locksByKeys = new Dictionary<string, object>();
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, () => SomeMethodToExecuteAlone());