I have a bunch of DB entities that are loaded into DB objects. The same DB entity may be loaded into more than DB object. Periodically a DB entity will require special processing. This processing must be performed by one thread at a time. Locking is in order here.
EDIT: Important note: the process calls a slow web service. This is what I'm trying to prevent concurrency. I don't see how this can be done safely w/o locks.
So I create an “padlock” object that will be referenced by the DB objects for locking. The padlock object is entity based so that two or more DB objects for the same entity will use the same padlock object. I’m storing these padlocks in a dictionary object using the DB entity’s ID as the key. The padlock object is just a simple string object as well. Is this the right approach? I'm thinking I'm either over engineering or simplifying this. If the approach is correct, how does this code look? It works, but I've yet to test it under load.
Thanks :)
public static func(CustomObject o)
{
if (ReadyForUpdate(o))
{
lock (LookupPadLockByID(object.ID)
{
if (ReadyForUpdate(o))
{
PerformUpdate(object);
}
}
}
}
private static readonly object padlockLock = new object();
private static readonly Dictionary<int, string> padLocks = new Dictionary<int,string>();
private static object LookupPadLockByID(int uniqueID)
{
lock (padlockLock)
{
if (!padLocks.ContainsKey(uniqueID))
{
padLocks.Add(uniqueID, uniqueID + " is locked");
}
}
return padLocks[uniqueID];
}