I have to lock objects by their keys (UIDs), do some staff and unlock. And I want to keep my dictionary clear. So here I use nested lock. The first is locking the whole dictionary just to safely perform RemoveLock(uid) at the end. And the second is locking an object to do stuff. My question is should i fear deadlock in this code?
private static readonly ConcurrentDictionary<Guid, object> _lockDict = new ConcurrentDictionary<Guid, object>();
private static object _listLock;
public static void RunWithLock(Guid uid, Action body)
{
lock (_listLock)
{
var obj = GetLock(uid);
lock (obj)
{
body();
}
RemoveLock(uid);
}
}
public static void RemoveLock(Guid uid)
{
_lockDict.TryRemove(uid, out _);
}
public static object GetLock(Guid uid)
{
return _lockDict.GetOrAdd(uid, s => new object());
}
Tried to run it, didn't get any deadlocks. But thousands of objects processing every minute can make it deadlock.