Reputation: 8112
private class MyClass
{
private static MyObject myObject = new MyObject();
private void ModifyObject()
{
lock(myObject)
{
myObject.UnsafeMethod();
}
}
}
Is it alright to lock on myObject
or must I declare another dedicated locking object?
Upvotes: 5
Views: 909
Reputation: 942468
It's fine, any object is good enough to act as a place to store the state of the lock.
It is a strong Red Flag in any code review however, hinting that the programmer is thinking about locks the wrong way. There is no such thing as "locking an object to make it thread-safe" in .NET. That notion does exist, the subject of much academic research, called STM or Software Transactional Memory. But there's not a shred of support for that in the .NET framework.
You use a lock to block code. Dangerous code that can be executed by more than one thread and reads or writes a variable. Very often in more than one place, code that exists in specific places in your source code file. You use a lock to ensure that only one thread can execute the code in these specific places at the same time. The lock state is therefore associated with sections of code, not an object. And should therefore require a dedicated object to store the lock state for those specific sections. You show that you know what you are doing by having such a dedicated object, instead of just picking one that you've got laying around. Also strongly self-documenting, making it much easier to see where a lock is taking place since you only have to search for the name of the locking variable.
Upvotes: 4
Reputation: 437864
It's fine to lock
on the object you want to synchronize access to, as long as you can be sure that all the code that locks on it is under your control (because otherwise, theoretically there could be code that you don't know about locking on the same object and causing a deadlock).
Most of the time you see dedicated lock objects exactly because of this: if you want to modify a collection that is exposed (e.g. through a property) good practice dictates that you cannot lock on the collection itself.
In this case the lock target is private
, so if you don't explicitly expose it to the outside world you are fine.
Upvotes: 2