In C#, it's well documented that locking on public objects is a bad idea, because we don't know who else might lock on that object, potentially causing problems like deadlocks. So we create private objects to serve as these locks. If we have a custom collection, for example, that needs to be able to modify items in a thread-safe way, we might want to be able to associate a unique private object with each item for locking.
As an example, instead of doing this:
lock (publicObject[i])
{
// modify publicObject[i]-related data
}
We should be doing something like this:
var lockObject = GetLockObject(i); // GetLockObject is private
lock (lockObject)
{
// modify publicObject[i]-related data
}
The former is much simpler when an object might be added, modified, or removed at any time, as creating or removing the associated object for locking requires some care. However, how to do that isn't a terribly hard problem, and it's not what I'm asking how to do here.
Instead of having a private object for locking for each item in the collection, it'd be much simpler to be able to have one private object that serves as "context" for the lock. Any other lock on the same public object that does not also use the same "context" will not block or be blocked by this code. If I could do something like this, it'd solve the problem of not knowing whether this object is used as a lock elsewhere, without me having to create a unique lock object for each thing I want to lock on. Something like this:
lock (_lockObject, publicObject[i])
{
// modify publicObject[i]-related data
}
We don't have to care if anything else outside this class is locking on publicObject[i]
, because they won't block or be blocked by this snippet. But inside this class, wherever I want to lock on publicObject
, I lock on the pair (_lockObject, publicObject[i])
instead.
But that obviously isn't a feature of C#, and locking on Tuples doesn't work, because they're value types. Is there a simple way to do this in C# at the moment? And by "simple" I mean simpler than maintaining a collection of corresponding objects for locking.
Thanks!