I want to lock on two objects at the same time.
Why can’t I write like such code?
lock (obj1, obj2)
Should I always write like that?
lock (obj1)
{
lock (obj2)
{
}
}
Probably this could be made simpler?
Likely it would be better to introduce special private object, and use it for a lock…
That is the correct way to lock on multiple objects, yes.
My guess is that the reason for only allowing a single argument to the lock statement is to make the order in which locks are taken as clear as possible.
Note that you must see to it that the two locks are taken in the same order everywhere in your code, or you have a potential for deadlocks.
You could also, as you suggest, introduce a single dedicated lock object, but that would make your locking more coarse. It all depends on your needs. If you sometimes only need one of the locks, you should keep them separate (but make sure to preserve lock ordering, as mentioned above).