I need to lock a section of code by string. Of course the following code is hideously unsafe:
lock(\"http://someurl\")
{
//bla
}
So I\'
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());
}