I have a method that should run exclusivley to run a block of code, but I want to add this restriction only if it is really necessary. Depending on the value of Id (Int32), I would load / modify various objects, so it makes no sense to block access for all threads. Here's the first attempt to do this -
private static readonly ConcurrentDictionary<int, Object> LockObjects = new ConcurrentDictionary<int, Object>(); void Method(int Id) { lock(LockObjects.GetOrAdd(Id,new Object()) {
I have doubts that this will work - TryRemove may fail (which will cause ConcurrentDictionary to continue to grow).
A more obvious error is that TryRemove successfully deletes the object, but if there are other threads (for the same Id) that are waiting (blocked) on this object, and then a new thread appears with the same identifier, adds a new object and starts processing, since no one else waits until the object is simply added.
Should I use TPL or some ConcurrentQueue to queue my tasks instead? What is the easiest solution?
source share